Rescore overlapping detections with Gaussian soft-NMS

Why it matters Soft-NMS is a drop-in change that improves recall for crowded objects such as people and cars.

Hard NMS deletes any box that overlaps a better one, which loses objects in crowded scenes. Soft-NMS lowers their scores instead.

Write soft_nms(boxes, scores, sigma=0.5, score_thresh=0.001). boxes is (n, 4) as (x1, y1, x2, y2), scores (n,). Keep a pool of all indices with their current scores. Repeat while the pool is not empty: pick the index with the highest current score (lowest index on ties), remove it from the pool and append (index, current score) to the output; then for every box left in the pool multiply its score by exp(-iou^2 / sigma), where iou is with the picked box; then drop pool boxes whose score is below score_thresh. Return (indices list, scores float array) in pick order.

Signaturedef soft_nms(boxes, scores, sigma=0.5, score_thresh=0.001)

Example

boxes [[0, 0, 2, 2], [0, 0, 2, 2], [5, 5, 6, 6]], scores [0.9, 0.8, 0.7] gives indices [0, 2, 1] and scores about [0.9, 0.7, 0.1083]: the duplicate is kept but pushed down by exp(-2).

Understand the idea

When two people stand close together, their detected boxes overlap. Hard NMS keeps the higher-scored box and deletes the other, losing a real person. Soft-NMS instead lowers the other box's score depending on how much it overlaps: a near-duplicate is pushed far down, a slight overlap is barely touched. Like a talent show where similar acts lose points rather than being disqualified.

Tiny example: two identical boxes with scores 0.9 and 0.8, and a far box with 0.7. Pick 0.9. The duplicate has IoU 1, so its score becomes 0.8 * exp(-1 / 0.5) = 0.108. The far box has IoU 0 and stays 0.7. Next picks: the far box, then the duplicate.

Rule: s_i = s_i * exp(-iou(M, b_i)^2 / sigma) for each remaining box after picking M.

Soft-NMS is a common post-processing option in two-stage detectors and pedestrian detection.

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

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

  • Sample 1: examplesoft_nms([[0.0, 0.0, 2.0, 2.0], [0.0, 0.0, 2.0, 2.0], [5.0, 5.0, 6.0, 6.0]], [0.9, 0.8, 0.7])
  • Sample 2: crowdsoft_nms([[0.0, 0.0, 4.0, 4.0], [1.0, 0.0, 5.0, 4.0], [2.0, 0.0, 6.0, 4.0], [10.0, 10.0, 12.0, 12.0]], [0.9...