Non-Maximum Suppression (NMS)
You are given a list of bounding box detections with confidence scores and must apply Non-Maximum Suppression to remove redundant overlapping detections.
Object detectors often produce multiple overlapping boxes for the same object. NMS keeps only the most confident detection and removes boxes that overlap significantly with it.
The algorithm:
- Sort all boxes by confidence score (descending)
- Select the highest-scoring box, add to keep list
- Remove all boxes with IoU > threshold with the selected box
- Repeat steps 2-3 until no boxes remain
- Return indices of kept boxes
Boxes with IoU > threshold are considered to be detecting the same object.
Example
boxes = [[0,0,10,10,0.9], [1,1,11,11,0.8], [50,50,60,60,0.7]] iou_threshold = 0.5
[0, 2]
- Input: three detections, each a box given by its top-left corner and bottom-right corner plus a confidence. Boxes 0 and 1 are squares shifted one pixel diagonally; box 2 is far away.
- Most confident first: box 0 (score ) is the strongest detection, so it survives no matter what.
- Box 1 vs box 0: they overlap on the square from to , so . Each box has area , so and . Box 1 is a duplicate of box 0 and is suppressed.
- Box 2 vs box 0: no overlap at all, so . Box 2 is a separate object and is kept.
- Output: the surviving indices in ascending order,
[0, 2]. - Notice that box 1's score of is high on its own; it is dropped only because a more confident box already covers the same object.
Constraints
- boxes: list of [x1, y1, x2, y2, score] where score is confidence
- iou_threshold: boxes with IoU > threshold are suppressed (typically 0.5)
- Return list of indices of kept boxes, sorted in ascending order