v9.1.1
Menu

Non-Maximum Suppression (NMS)

hardPROObject DetectionDetectionCV: Recognition

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:

  1. Sort all boxes by confidence score (descending)
  2. Select the highest-scoring box, add to keep list
  3. Remove all boxes with IoU > threshold with the selected box
  4. Repeat steps 2-3 until no boxes remain
  5. Return indices of kept boxes

IoU(A,B)=∣A∩B∣∣A∪B∣IoU(A, B) = \frac{|A \cap B|}{|A \cup B|}

Boxes with IoU > threshold are considered to be detecting the same object.

Example

Input
boxes = [[0,0,10,10,0.9], [1,1,11,11,0.8], [50,50,60,60,0.7]]
iou_threshold = 0.5
Output
[0, 2]
Reasoning
  • Input: three detections, each a box given by its top-left corner (x1,y1)(x_1, y_1) and bottom-right corner (x2,y2)(x_2, y_2) plus a confidence. Boxes 0 and 1 are 10×1010 \times 10 squares shifted one pixel diagonally; box 2 is far away.
  • Most confident first: box 0 (score 0.90.9) is the strongest detection, so it survives no matter what.
  • Box 1 vs box 0: they overlap on the square from (1,1)(1,1) to (10,10)(10,10), so ∣A∩B∣=9×9=81|A \cap B| = 9 \times 9 = 81. Each box has area 100100, so ∣A∪B∣=100+100−81=119|A \cup B| = 100 + 100 - 81 = 119 and IoU=81/119≈0.68>0.5IoU = 81/119 \approx 0.68 > 0.5. Box 1 is a duplicate of box 0 and is suppressed.
  • Box 2 vs box 0: no overlap at all, so IoU=0≤0.5IoU = 0 \le 0.5. 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 0.80.8 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

Learn this in

More from CV: Recognition

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.