Sub topic 3
Duplicate detections and non-maximum suppression
This chapter assumes you can read basic Python and that you know how to compute IoU for two boxes, as in the previous chapter. It also assumes you know a detector outputs a box, a class label, and a confidence score for each detection. By the end you will be able to explain why detectors emit duplicates and write greedy non-maximum suppression (NMS). You will also know how its threshold affects the metrics we build later.
Why detectors produce duplicates
Most detectors do not emit one box per object. They predict from many places at once: anchor boxes, grid cells, or feature-map positions. A single dog covers dozens of these positions, and each position can fire with a good box and a high score. The raw output of a detector often looks like a cluster of near-identical boxes around each object, plus a scattering of low-score boxes on background.
For a user, duplicates are clutter. For evaluation, they do real damage. Each ground-truth box can be matched by only one detection (the matching chapter covers this). The first detection that overlaps it becomes a true positive, and every later one becomes a false positive, even though the box is in the right place. A detector that finds every object but emits three boxes per object has recall near 1 and precision near 0.33.
Non-maximum suppression is the standard post-processing step that removes these duplicates. It runs after the network and before scoring.
The greedy NMS algorithm
NMS keeps the highest-scoring box in each cluster and discards the boxes that overlap it too much. The procedure, for one class:
- Sort all detections by score, highest first.
- Take the top detection and add it to the keep list.
- Remove every remaining detection whose IoU with that box is above a threshold.
- Repeat from step 2 until nothing is left.
The threshold is a hyperparameter, commonly 0.5 for general detectors and sometimes 0.6 or 0.7. It is a separate setting from the IoU threshold used later to decide whether a detection matches a ground-truth box. The two thresholds answer different questions. The NMS threshold asks whether two detections are the same object. The evaluation threshold asks whether a detection is correct.
A working implementation
The code below reuses the iou function from the previous chapter, then implements NMS directly from the steps above. It suppresses a box only when its IoU is strictly greater than the threshold.
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2) with x1 < x2 and y1 < y2."""
ix1 = max(a[0], b[0])
iy1 = max(a[1], b[1])
ix2 = min(a[2], b[2])
iy2 = min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
def nms(boxes, scores, iou_threshold=0.5):
"""Greedy NMS for one class. Returns the indices of the kept boxes."""
order = sorted(range(len(boxes)), key=lambda i: -scores[i])
keep = []
while order:
best = order.pop(0)
keep.append(best)
order = [i for i in order if iou(boxes[best], boxes[i]) <= iou_threshold]
return keep
boxes = [(0, 0, 10, 10), (1, 1, 11, 11), (20, 20, 30, 30), (8, 8, 18, 18)]
scores = [0.9, 0.8, 0.7, 0.5]
print(nms(boxes, scores, 0.5)) # [0, 2, 3]
print(nms(boxes, scores, 0.7)) # [0, 1, 2, 3]Walk through the first call. Box 0 has the top score and is kept. Box 1 overlaps it with IoU 81 / 119, about 0.68, which is above 0.5, so box 1 is dropped. Box 2 is far away and survives, as does box 3, whose IoU with box 0 is only 4 / 196, about 0.02. Box 2 is then kept, and box 3 does not overlap it. The result is the indices 0, 2, 3.
At threshold 0.7 the same box 1 is not suppressed, because 0.68 is below 0.7. Raising the threshold makes NMS more tolerant of overlap, so more boxes survive.
Run NMS per class
Boxes of different classes should not suppress each other. A person on a horse produces heavily overlapping boxes, and both are correct. If NMS ignored labels, the lower-scoring one could be removed.
The usual approach is to run NMS separately within each class label. The function below does that and reuses nms from above.
def nms_per_class(boxes, scores, labels, iou_threshold=0.5):
"""Class-wise NMS. Returns the sorted indices of the kept boxes."""
keep = []
for label in set(labels):
idx = [i for i, l in enumerate(labels) if l == label]
kept = nms([boxes[i] for i in idx], [scores[i] for i in idx], iou_threshold)
keep.extend(idx[k] for k in kept)
return sorted(keep)
labels = ["cat", "dog", "cat", "cat"]
print(nms_per_class(boxes, scores, labels, 0.5)) # [0, 1, 2, 3]
print(nms(boxes, scores, 0.5)) # [0, 2, 3] (class-agnostic)Box 1 survives in the class-wise version because it is the only dog and nothing competes with it. In the class-agnostic version it is suppressed by the cat box.
Class-wise NMS is the default in most pipelines, and it is also what evaluation assumes, because mAP is computed one class at a time. Class-agnostic NMS is sometimes used when a model confuses similar classes and you want only one label per object. If you do that, say so when you report results.
In PyTorch you would normally call torchvision.ops.nms or torchvision.ops.batched_nms, which runs class-wise NMS in one call. The logic is the same as the code above, but it runs on tensors and is much faster.
The threshold is a trade-off
The NMS threshold controls two failure modes that pull in opposite directions.
| Threshold | Effect on duplicates | Effect on crowded scenes |
|---|---|---|
| Low (for example 0.3) | Removes nearly all duplicates, even loosely overlapping ones | Suppresses real neighbours, so recall drops |
| Medium (about 0.5) | Removes most duplicates | Merges some touching objects |
| High (for example 0.8) | Leaves many near-duplicates | Keeps neighbours, but each extra box is a false positive |
A low threshold hurts when real objects overlap, as with a crowd of people or stacked boxes. Two true objects with IoU 0.45 between their boxes would both survive at 0.5, but one would be removed at 0.3. A high threshold lets partial duplicates through. These then appear in the evaluation as false positives, which lowers precision and so AP.
The right value depends on how much your objects overlap in the data. Tune it on a validation set by watching the metric, not by guessing.
How duplicates change the metric
Take the example from the AP code in the spine: two ground-truth boxes and three detections. The first detection (score 0.9) matches the first object. The second (score 0.8) is a slightly shifted copy of it with IoU 0.81. The third (score 0.7) matches the second object.
Without NMS, the duplicate is a false positive. The precision sequence is 1.0, 0.5, 0.67 and AP comes out as about 0.83. If NMS removes the duplicate, the sequence is 1.0, 1.0 and AP is 1.0. One duplicate cost 0.17 of AP in a tiny example. In a real run with thousands of detections, systematic duplicates lower the whole precision-recall curve.
NMS also has a quieter interaction with the metric. NMS can only help evaluation if it keeps the correct box. It keeps the highest-scoring one, not the best-localized one. If a poorly aligned box has a slightly higher score than a tight one, the tight one is removed, and the surviving box may fall below the IoU threshold. This is one reason why high IoU thresholds in COCO-style mAP are sensitive to how well scores reflect localization quality.
Soft-NMS: decay instead of delete
Hard NMS is all-or-nothing. A box that overlaps the winner slightly above the threshold is deleted, even if it is a true neighbour. Soft-NMS keeps every box but lowers the score of overlapping ones by a factor that grows with IoU. A common form is Gaussian decay: the new score is score * exp(-iou**2 / sigma).
import math
def soft_nms(boxes, scores, sigma=0.5, score_threshold=0.001):
"""Gaussian Soft-NMS. Returns (box, score) pairs in the order they were picked."""
boxes, scores = list(boxes), list(scores)
result = []
while boxes:
m = max(range(len(scores)), key=lambda i: scores[i])
box, score = boxes.pop(m), scores.pop(m)
result.append((box, score))
scores = [s * math.exp(-iou(box, b) ** 2 / sigma) for b, s in zip(boxes, scores)]
kept = [i for i, s in enumerate(scores) if s >= score_threshold]
boxes = [boxes[i] for i in kept]
scores = [scores[i] for i in kept]
return result
for box, score in soft_nms(boxes, scores):
print(box, round(score, 2))
# (0, 0, 10, 10) 0.9
# (20, 20, 30, 30) 0.7
# (8, 8, 18, 18) 0.5
# (1, 1, 11, 11) 0.32The duplicate at (1, 1, 11, 11) is not deleted. Its score falls from 0.8 to about 0.32 and it moves to the bottom of the ranking. In an AP calculation, a low-ranked false positive costs far less than a high-ranked one, because it appears late in the curve, after most of the recall has been reached. Soft-NMS therefore tends to raise AP on crowded data. The cost is that low-score duplicates remain in the output, so you need a score threshold or a per-image cap on detections before showing results to a user.
Practical rules and common errors
- Apply NMS before matching, not after. Evaluation code such as the
average_precisionfunction assumes the detections are already deduplicated. It treats extra boxes as false positives by design. - Do not filter by confidence before AP. A cut at 0.5 removes the tail of the ranking, so the curve ends early and recall cannot reach its true value. Use a very low score floor, such as 0.001, and let AP handle the ranking. Evaluation protocols usually cap the number of detections per image (COCO uses 100).
- Keep the thresholds apart. Changing the NMS threshold changes the detections. Changing the evaluation IoU threshold changes how they are judged. Report both.
- Check the boundary rule. Some libraries suppress at IoU greater than the threshold and others at greater than or equal. For continuous scores this seldom matters, but it matters for test cases with exact values.
- Mind the cost. NMS compares boxes pairwise, so the worst case grows with the square of the number of boxes. Pre-select the top few thousand boxes by score before running it.
- Know the alternatives. Some detectors, such as DETR, are trained with one-to-one matching so they produce few duplicates and need no NMS. The metric is unchanged, but there is no NMS threshold to tune.
Exercises
Exercise
Three boxes of one class: P = (0, 0, 10, 10) with score 0.8, Q = (0, 0, 10, 5) with score 0.9, and R = (0, 5, 10, 10) with score 0.7. Run greedy NMS with threshold 0.5, suppressing only when IoU is strictly greater than the threshold. Which boxes survive? What changes if you suppress when IoU is greater than or equal to the threshold?
Show answer
Q is kept first. IoU(Q, P) = 50 / 100 = 0.5 and IoU(Q, R) = 0, so neither is suppressed. P is kept next. IoU(P, R) = 50 / 100 = 0.5, which is not above 0.5, so R is kept too. All three survive. With the greater-than-or-equal rule, P is suppressed by Q because 0.5 is not below the threshold. R then has IoU 0 with Q and survives, so the result is Q and R.
Exercise
Your evaluation script drops every detection with a score below 0.5 before computing AP, and the reported AP is lower than the one from a reference script. Explain why, and say what you would change.
Show answer
Dropping low-score detections cuts the tail of the ranked list. The precision-recall curve then stops at a recall below what the detector could reach, and the area added by that tail is lost, so AP is underestimated. Keep all detections above a very low score floor such as 0.001 (with a per-image cap such as 100), apply class-wise NMS, and let AP integrate over the whole ranking.