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.

Signaturedef nms(boxes, scores, thresh)

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. Worked example: 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]. Rule: 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: two objectsnms(_b, _s, 0.5)
  • Sample 2: strict threshold keeps morenms(_b, _s, 0.85)