Sub topic 6
Removing duplicate boxes with non-maximum suppression
This chapter assumes you can read boxes in (x1, y1, x2, y2) format and compute intersection over union (IoU), as covered in the earlier chapters. It also assumes you know that a detector produces many candidate boxes per image.
Why duplicates appear
A single-stage detector like YOLO predicts boxes from many grid cells and several scales. Neighbouring cells all see part of the same object. Each one can produce a confident box around it. Before any cleanup, one dog may have five or ten overlapping predictions with slightly different positions and scores.
Non-maximum suppression (NMS) is a post-processing step that keeps the best box for each object and discards the rest. It runs after the network, not inside training, and it uses only box coordinates and scores.
The core idea is simple. If two boxes of the same class overlap heavily, they probably describe the same object. Keep the one with the higher score.
The greedy algorithm
Greedy NMS for one class works as follows:
- Sort all boxes by score, highest first.
- Take the top box and add it to the keep list.
- Remove every remaining box whose IoU with that box is at or above the IoU threshold.
- Repeat from step 2 until no boxes remain.
Here is the implementation, using the iou function from the previous chapter. It is repeated so the code runs on its own.
def iou(a, b):
# Boxes are (x1, y1, x2, y2) in the same coordinate system.
ax1, ay1, ax2, ay2 = a
bx1, by1, bx2, by2 = b
ix1, iy1 = max(ax1, bx1), max(ay1, by1)
ix2, iy2 = min(ax2, bx2), min(ay2, by2)
inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
union = (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - inter
return inter / union if union > 0 else 0.0
def nms(boxes, scores, iou_thr=0.5):
# Greedy NMS for a single class; returns indices of boxes to keep.
order = sorted(range(len(boxes)), key=lambda i: scores[i], reverse=True)
keep = []
while order:
best = order.pop(0)
keep.append(best)
order = [j for j in order if iou(boxes[best], boxes[j]) < iou_thr]
return keep
boxes = [
(100, 100, 200, 200), # object A, score 0.90
(105, 98, 205, 202), # object A again, score 0.80
(110, 110, 210, 210), # object A again, score 0.60
(300, 300, 380, 380), # object B, score 0.70
]
scores = [0.90, 0.80, 0.60, 0.70]
print(nms(boxes, scores, iou_thr=0.5)) # [0, 3]Box 0 wins and suppresses boxes 1 and 2, because both overlap it with IoU above 0.5. Box 3 does not overlap box 0, so it survives.
Worked trace
Trace the example above by hand.
- Sorted order by score is
[0, 1, 3, 2]. - Pick box 0. Its IoU with box 1 is about 0.82, so box 1 is dropped. Its IoU with box 2 is about 0.68, so box 2 is dropped. Its IoU with box 3 is 0, so box 3 stays.
- Pick box 3. Nothing remains. The result is
[0, 3].
The cost is roughly quadratic in the number of boxes in the worst case. That is why detectors filter by confidence first. Low-score boxes never enter the loop.
Per-class NMS
The function above handles one class. A real detector emits boxes for many classes, and NMS should not let a high-scoring "person" box suppress a "bicycle" box that overlaps it. A rider on a bicycle is the standard case. The two boxes overlap a lot, and both are correct.
The usual approach is to run NMS separately for each class. A common trick is the offset method. You add a large class-dependent offset to every coordinate, so boxes of different classes never overlap, and then run one NMS pass.
def batched_nms(boxes, scores, class_ids, iou_thr=0.5):
# Run greedy NMS independently for each class; returns kept indices.
keep = []
for c in sorted(set(class_ids)):
idx = [i for i, k in enumerate(class_ids) if k == c]
sub_boxes = [boxes[i] for i in idx]
sub_scores = [scores[i] for i in idx]
for j in nms(sub_boxes, sub_scores, iou_thr):
keep.append(idx[j])
return sorted(keep, key=lambda i: scores[i], reverse=True)
boxes = [(0, 0, 100, 100), (5, 5, 105, 105), (10, 10, 90, 90)]
scores = [0.9, 0.8, 0.7]
class_ids = [0, 0, 1] # person, person, bicycle
print(batched_nms(boxes, scores, class_ids)) # [0, 2]The second person box is suppressed. The bicycle box is kept even though it lies inside the first box, because it belongs to a different class.
Some pipelines use class-agnostic NMS, which ignores class labels. This removes cases where the model labels one object as both "cat" and "dog". It also risks removing legitimate overlapping objects of different classes. Choose it only when your classes are mutually exclusive in space.
The IoU threshold
The IoU threshold controls how aggressive suppression is.
| IoU threshold | Effect | Typical risk |
|---|---|---|
| Low (about 0.3) | Suppresses boxes with modest overlap | Merges nearby real objects, so recall drops in crowds |
| Medium (0.5 to 0.7) | Balanced for most scenes | Occasional duplicates or occasional merged neighbours |
| High (about 0.9) | Only near-identical boxes are removed | Many duplicate boxes remain, so precision drops |
A lower threshold removes more boxes. A higher threshold keeps more. This is easy to reverse in your head, so check it with the code. A box is dropped when its IoU is at or above the threshold. A higher threshold means fewer boxes meet that condition.
In Ultralytics the NMS IoU threshold is the iou argument to predict. It is separate from the confidence threshold conf, which removes low-score boxes before NMS runs. The default iou is 0.7 in current releases.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.predict("bus.jpg", conf=0.25, iou=0.7)
for r in results:
for box in r.boxes:
cls_id = int(box.cls[0])
score = float(box.conf[0])
x1, y1, x2, y2 = box.xyxy[0].tolist()
print(model.names[cls_id], round(score, 2), [round(v) for v in (x1, y1, x2, y2)])Try running this with iou=0.3 and then iou=0.95 on an image with a crowd. Compare the number of boxes printed.
Common errors and edge cases
- Wrong order of operations. Apply the confidence filter first, then NMS. Running NMS on all raw boxes is slow, and low-score boxes can suppress nothing useful anyway.
- Mixed coordinate formats. The
ioufunction assumes corner format. If boxes are in centre format(cx, cy, w, h), results are wrong and no error is raised. Convert first. - Crowded scenes. Pedestrians in a dense crowd overlap above any reasonable threshold. Greedy NMS removes true objects. Raising the threshold helps but adds duplicates. This trade-off is one reason for variants such as Soft-NMS.
- Ties in score. Python's sort is stable, so equal scores keep input order. Results can differ between implementations. This rarely matters, but it can make exact comparisons in tests fail.
- Score semantics. NMS ranks by whatever score you give it. In older YOLO versions this is objectness times class probability. In newer anchor-free versions it is the class score. Ranking by the wrong quantity keeps the wrong box.
- Evaluation interaction. Mean average precision (mAP) evaluation uses a very low confidence threshold, so many more boxes reach NMS. Metrics computed with different NMS settings are not comparable.
Variants worth knowing
Soft-NMS does not delete overlapping boxes. It lowers their scores in proportion to the overlap, so boxes that are truly separate objects can still survive with reduced confidence. Weighted box fusion averages overlapping boxes instead of picking one, which is common when combining several models. DIoU-NMS adds the distance between box centres to the overlap measure, which helps in crowds.
Some recent YOLO releases are trained to produce one box per object directly. They are called NMS-free or end-to-end models. They remove the post-processing step and its threshold, but they need a matching training scheme, so you cannot simply switch NMS off on a model that was trained to expect it.
Exercise
Three boxes of the same class have scores 0.9, 0.85 and 0.4. Box 1 (0.9) and box 2 (0.85) have an IoU of 0.6 with each other. Box 3 (0.4) does not overlap either. With an NMS IoU threshold of 0.5, which boxes remain? Which remain at a threshold of 0.7?
Show answer
At 0.5, box 1 is kept first, and box 2 is dropped because 0.6 is at or above 0.5. Box 3 is kept. The result is boxes 1 and 3. At 0.7, the IoU of 0.6 is below the threshold, so box 2 is not suppressed. All three boxes remain.
Exercise
A street camera model correctly detects a person riding a bicycle, but after you enable class-agnostic NMS the bicycle disappears. Why, and what should you do?
Show answer
Class-agnostic NMS ignores labels, so the higher-scoring person box suppresses the overlapping bicycle box. Switch back to per-class NMS, so each class is suppressed only by boxes of the same class.