Non-Maximum Suppression: Pruning Duplicate Boxes

Computer VisionMedium+20 XP+15

Non-Maximum Suppression: Pruning Duplicate Boxes

A detector doesn't find one box per object — it finds a dozen nearly identical ones. NMS is the greedy cleanup that keeps only the best of each pile:

  1. Take the highest-scoring box that's still in play and keep it.
  2. Discard every remaining box whose IoU with it exceeds iou_threshold — those are duplicates of the same object.
  3. Repeat with what's left.

Task: write nms(boxes, scores, iou_threshold) where boxes is a list of [x1, y1, x2, y2] and scores is the matching confidence for each. Return the list of kept indices, in the order they were kept (so highest score first).

  • Boxes are removed only when IoU is strictly greater than the threshold — exactly equal survives.
  • If two boxes tie on score, the lower index goes first.
  • Empty input returns an empty list.

Note what the threshold does. Set it high and you keep near-duplicates; set it low and you start deleting genuinely separate objects that happen to stand close together.

Examples

boxes = [[0.0, 0.0, 2.0, 2.0], [0.1, 0.1, 2.1, 2.1], [5.0, 5.0, 7.0, 7.0]]
scores = [0.9, 0.8, 0.7]
iou_threshold = 0.5
returns [0, 2]
boxes = [[0.0, 0.0, 1.0, 1.0], [2.0, 2.0, 3.0, 3.0]]
scores = [0.5, 0.9]
iou_threshold = 0.5
returns [1, 0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run