318. Remove duplicate detections with IoU and non-max suppression
Object detectors output many overlapping boxes for the same object. Non-max suppression keeps the best box and drops any box that overlaps it too much, then repeats.
Boxes are [x1, y1, x2, y2] with x2 > x1 and y2 > y1. IoU = intersection area / union area.
Write nms(boxes, scores, thresh). Repeatedly take the remaining box with the highest score (ties: lower index), keep it, and remove every remaining box whose IoU with it is GREATER than thresh. Return kept indices in the order they were kept.
def nms(boxes, scores, thresh)Example 1
Input: nms([[0, 0, 10, 10], [1, 1, 11, 11], [20, 20, 30, 30], [0, 0, 9, 10], [21, 21, 29, 29]], [0.9, 0.8, 0.7, 0.95, 0.6], 0.5)
Output: [3, 2]
Example 2
Input: boxes = [[0, 0, 10, 10], [1, 1, 11, 11], [20, 20, 30, 30], [0, 0, 9, 10], [21, 21, 29, 29]], scores = [0.9, 0.8, 0.7, 0.95, 0.6], thresh = 0.85
Output: [3, 1, 2, 4]
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Write iou(a, b) first: overlap width = max(0, min(x2) - max(x1)), same for height.
Hint 2
Then a while loop over a sorted list of indices.
Common mistakes
- Union is area A plus area B minus the intersection; forgetting to subtract it (the buggy version) halves IoU for identical boxes.
Understand the idea
Object detectors often draw several boxes around one object. IoU (intersection over union) measures overlap: shared area divided by total covered area, from 0 (no overlap) to 1 (same box). Non-max suppression keeps the highest-scoring box, deletes boxes that overlap it too much, then repeats with what is left.
A = [0, 0, 2, 2] (area 4, score 0.9), B = [1, 1, 3, 3] (area 4, score 0.8), C = [0, 0, 2, 1] (area 2, score 0.7), threshold 0.4. A and B share [1, 1, 2, 2], area 1; union = 4 + 4 - 1 = 7; IoU = 0.143. A and C share area 2; union = 4 + 2 - 2 = 4; IoU = 0.5. Keep A first, remove C (0.5 > 0.4), keep B. Result [0, 1].
intersection width and height = max(0, min(x2s) - max(x1s)) and likewise for y; IoU = inter / (areaA + areaB - inter); remove when IoU > thresh
YOLO and most detectors run NMS after prediction.