Non-Maximum Suppression
A detector scores thousands of candidate boxes, and a good one fires on many candidates around every object: neighbouring windows, anchors or grid cells all see the same car. Left alone, one car becomes five detections, and four of them are false positives in the evaluation. Non-maximum suppression (NMS) is the post-processing step that keeps the best box of each cluster and removes the rest. It is a dozen lines of code, it runs after almost every detector built before 2020 and most built since, and its one threshold decides whether a detector can see two people standing close together.
Green boxes are the two people, red boxes the detector's candidates.
Greedy NMS
The standard algorithm is greedy:
- Sort the boxes by score, highest first.
- Take the top box and keep it.
- Remove every remaining box with (typically to ).
- Repeat from step 2 with what is left.
It is "non-maximum suppression" because a box survives only if no better-scoring box overlaps it by more than : it must be a local maximum of the score. The worst case is IoU computations for boxes, which is why detectors first drop boxes under a low score threshold (0.001 to 0.05) and cap the input (YOLO's default is 30,000 candidates before NMS and 300 after).
Six candidates from the figure, plus a bicycle under the first person and a small false alarm:
import numpy as np
def iou_one_to_many(b, others):
iw = (np.minimum(b[2], others[:, 2]) - np.maximum(b[0], others[:, 0])).clip(0)
ih = (np.minimum(b[3], others[:, 3]) - np.maximum(b[1], others[:, 1])).clip(0)
inter = iw * ih
area = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
return inter / (area(b) + area(others) - inter)
def nms(boxes, scores, thr, verbose=False):
boxes, scores = np.asarray(boxes, float), np.asarray(scores, float)
order = np.argsort(-scores, kind="stable")
keep = []
while order.size:
i, order = order[0], order[1:]
keep.append(int(i))
ious = iou_one_to_many(boxes[i], boxes[order])
if verbose and (ious > thr).any():
print(f" keep {i} ({scores[i]:.2f}), remove {order[ious > thr].tolist()} with IoU {ious[ious > thr].round(2).tolist()}")
order = order[ious <= thr]
return keep
boxes = np.array([[50, 40, 150, 240], [55, 45, 152, 250], [45, 30, 145, 230], [52, 70, 140, 230], # person A
[160, 50, 260, 245], [168, 62, 262, 252], # person B
[50, 120, 160, 250], # bicycle under A
[300, 100, 330, 130]]) # false alarm
scores = np.array([0.92, 0.85, 0.70, 0.55, 0.88, 0.60, 0.80, 0.30])
labels = np.array([0, 0, 0, 0, 0, 0, 1, 0]) # 0 person, 1 bicycle
keep = nms(boxes, scores, 0.5, verbose=True)
print("kept, class-agnostic, IoU 0.5:", keep) keep 0 (0.92), remove [1, 6, 2, 3] with IoU [0.87, 0.54, 0.82, 0.7]
keep 4 (0.88), remove [5] with IoU [0.82]
kept, class-agnostic, IoU 0.5: [0, 4, 7]
The 0.92 box removes three duplicates, the 0.88 box removes one, and the false alarm survives because it overlaps nothing: NMS removes duplicates, not mistakes. That is the score threshold's job. But one kept box is wrong in another way: the bicycle under person A has been removed, because it overlaps the person box by more than 0.5. Class-agnostic NMS treats a person on a bicycle as a duplicate.
Class-aware NMS and the offset trick
Class-aware (per-class, "batched") NMS runs the algorithm separately for every class, so boxes of different classes never suppress each other. It is the default in torchvision's detectors and in Ultralytics (agnostic_nms=False). Running a loop over classes is slow on a GPU, so libraries use a trick: shift every box by its class id times a large offset, so boxes of different classes cannot overlap, and run one plain NMS.
Class-agnostic NMS still has a use: when a model gives the same object two labels ("cat 0.81" and "dog 0.45" on the same box), class-aware NMS keeps both, one of which is a false positive. Which one to use depends on whether objects of different classes really overlap in your data (riders and bicycles, people and chairs) or not (cells under a microscope, one product per shelf slot).
import numpy as np
def iou_one_to_many(b, others):
iw = (np.minimum(b[2], others[:, 2]) - np.maximum(b[0], others[:, 0])).clip(0)
ih = (np.minimum(b[3], others[:, 3]) - np.maximum(b[1], others[:, 1])).clip(0)
area = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
return iw * ih / (area(b) + area(others) - iw * ih)
def nms(boxes, scores, thr):
boxes, scores = np.asarray(boxes, float), np.asarray(scores, float)
order, keep = np.argsort(-scores, kind="stable"), []
while order.size:
i, order = order[0], order[1:]
keep.append(int(i))
order = order[iou_one_to_many(boxes[i], boxes[order]) <= thr]
return keep
def nms_per_class(boxes, scores, labels, thr):
keep = []
for c in np.unique(labels):
idx = np.flatnonzero(labels == c)
keep += idx[nms(boxes[idx], scores[idx], thr)].tolist()
return sorted(keep, key=lambda i: -scores[i])
def nms_offset_trick(boxes, scores, labels, thr):
shifted = boxes + labels[:, None] * (boxes.max() + 1) # each class in its own far-away region
return nms(shifted, scores, thr)
boxes = np.array([[50, 40, 150, 240], [55, 45, 152, 250], [45, 30, 145, 230], [52, 70, 140, 230],
[160, 50, 260, 245], [168, 62, 262, 252], [50, 120, 160, 250], [300, 100, 330, 130],
[400, 150, 480, 220], [402, 148, 481, 223]]) # + one animal with two labels
scores = np.array([0.92, 0.85, 0.70, 0.55, 0.88, 0.60, 0.80, 0.30, 0.81, 0.45])
labels = np.array([0, 0, 0, 0, 0, 0, 1, 0, 2, 3]) # person, bicycle, cat, dog
names = ["person", "bicycle", "cat", "dog"]
for title, keep in [("agnostic", nms(boxes, scores, 0.5)),
("per class", nms_per_class(boxes, scores, labels, 0.5)),
("offset trick", nms_offset_trick(boxes, scores, labels, 0.5))]:
print(f"{title:12s}", keep, [names[labels[i]] for i in keep])agnostic [0, 4, 8, 7] ['person', 'person', 'cat', 'person']
per class [0, 4, 8, 6, 9, 7] ['person', 'person', 'cat', 'bicycle', 'dog', 'person']
offset trick [0, 4, 8, 6, 9, 7] ['person', 'person', 'cat', 'bicycle', 'dog', 'person']
The per-class loop and the offset trick keep the same boxes, so the trick is exact (it only needs the offset to be larger than any coordinate). Class-aware NMS saves the bicycle and also keeps the "dog 0.45" label on the cat; agnostic NMS removes both. Neither is right everywhere.
Crowds: the threshold dilemma
Greedy NMS cannot tell a duplicate from a second object that overlaps the first. Both are just "a box with IoU above and a lower score". People in a queue, cars in a traffic jam and fruit on a tree overlap heavily, and NMS removes real objects there.
To measure it, the next example builds crowded scenes: rows of six 40 x 100 pixel "people", with left edges 8 to 30 pixels apart and small vertical offsets, so neighbouring ground-truth boxes overlap with IoU up to about 0.6. A simulated detector fires 6 times on each person (boxes jittered by 3 pixels, scores between 0.5 and 0.95) and adds 3 random false alarms per scene with low scores. NMS at different thresholds is then scored on 100 scenes with AP@0.5 (detection metrics) and the counts of true positives, duplicates and missed people among detections with score above 0.5.
import numpy as np
def iou_matrix(a, b):
a, b = np.asarray(a, float)[:, None], np.asarray(b, float)[None]
iw = (np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0])).clip(0)
ih = (np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1])).clip(0)
area = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
return iw * ih / (area(a) + area(b) - iw * ih)
def nms(boxes, scores, thr):
order, keep = np.argsort(-scores, kind="stable"), []
while order.size:
i, order = order[0], order[1:]
keep.append(int(i))
order = order[iou_matrix(boxes[i:i + 1], boxes[order])[0] <= thr]
return keep
def crowd_scene(rng, n=6):
"""A row of n people, 40 x 100 px, gaps of 8..30 px between left edges; a detector with 6 hits per person."""
x = 20 + np.cumsum(rng.integers(8, 31, n)); y = rng.integers(20, 40, n)
gt = np.c_[x, y, x + 40, y + 100].astype(float)
boxes = np.repeat(gt, 6, axis=0) + rng.normal(0, 3, (6 * n, 4))
scores = rng.uniform(0.5, 0.95, 6 * n)
fa = rng.uniform(0, 300, (3, 2)); fa = np.c_[fa, fa + [40, 100]] # 3 false alarms
return gt, np.r_[boxes, fa], np.r_[scores, rng.uniform(0.05, 0.6, 3)]
def evaluate(scenes, post):
"""AP@0.5 over all scenes, plus TP / duplicate / missed counts at score > 0.5."""
rows, n_gt, tp_hi, dup_hi, miss_hi = [], 0, 0, 0, 0
for gt, boxes, scores in scenes:
b, s = post(boxes, scores)
used, used_hi = set(), set()
for k in np.argsort(-s, kind="stable"):
m = iou_matrix(b[k:k + 1], gt)[0]; j = int(m.argmax())
hit = m[j] >= 0.5 and j not in used
used |= {j} if hit else set(); rows.append((s[k], hit))
if s[k] > 0.5:
if hit: tp_hi += 1; used_hi.add(j)
elif m[j] >= 0.5: dup_hi += 1
n_gt += len(gt); miss_hi += len(gt) - len(used_hi)
rows.sort(key=lambda r: -r[0]); tp = np.array([r[1] for r in rows], float)
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / n_gt
ap = np.sum(np.diff(np.r_[0, rec]) * np.maximum.accumulate(prec[::-1])[::-1])
return ap, tp_hi, dup_hi, miss_hi, n_gt
rng = np.random.default_rng(0)
scenes = [crowd_scene(rng) for _ in range(100)]
gt0 = scenes[0][0]
print("IoU of neighbours in scene 0:", [round(float(iou_matrix(gt0[i:i + 1], gt0[i + 1:i + 2])[0, 0]), 2) for i in range(5)])
ap, tp, dup, miss, n = evaluate(scenes, lambda b, s: (b, s))
print(f"no NMS AP@0.5 {ap:.3f} | score>0.5: TP {tp}, duplicates {dup}, missed {miss} of {n}")
for thr in [0.3, 0.4, 0.5, 0.6, 0.7, 0.8]:
ap, tp, dup, miss, n = evaluate(scenes, lambda b, s: (b[nms(b, s, thr)], s[nms(b, s, thr)]))
print(f"NMS IoU {thr}: AP@0.5 {ap:.3f} | score>0.5: TP {tp}, duplicates {dup}, missed {miss} of {n}")IoU of neighbours in scene 0: [0.29, 0.34, 0.39, 0.43, 0.6]
no NMS AP@0.5 0.736 | score>0.5: TP 600, duplicates 3002, missed 0 of 600
NMS IoU 0.3: AP@0.5 0.711 | score>0.5: TP 426, duplicates 0, missed 174 of 600
NMS IoU 0.4: AP@0.5 0.823 | score>0.5: TP 494, duplicates 0, missed 106 of 600
NMS IoU 0.5: AP@0.5 0.923 | score>0.5: TP 554, duplicates 0, missed 46 of 600
NMS IoU 0.6: AP@0.5 0.976 | score>0.5: TP 587, duplicates 18, missed 13 of 600
NMS IoU 0.7: AP@0.5 0.960 | score>0.5: TP 600, duplicates 227, missed 0 of 600
NMS IoU 0.8: AP@0.5 0.847 | score>0.5: TP 600, duplicates 977, missed 0 of 600
Read the table from both ends:
- No NMS: every person is found, but with 3,002 duplicates among the confident detections, and AP@0.5 is 0.736. Duplicates pull precision down.
- Threshold too low (0.3): no duplicates at all, but 174 of the 600 people are gone: whenever two people overlap with IoU above 0.3, the less confident one is "suppressed". AP@0.5 drops to 0.711, worse than no NMS.
- Threshold too high (0.8): every person survives, and so do 977 duplicates: two boxes jittered by a few pixels around the same 40-pixel-wide person often overlap by less than 0.8, so neither suppresses the other.
- In between: 0.6 is the best here (AP 0.976, 13 people lost, 18 duplicates). The best value depends on how crowded the data is, so treat the NMS threshold as a hyperparameter and tune it on validation data, like the score threshold.
No threshold gets both numbers to zero, because a duplicate and a close neighbour can have the same IoU with the kept box. That is the crowd problem.
Soft-NMS
Soft-NMS (Bodla et al., 2017) does not delete an overlapping box; it lowers its score, more for larger overlap, and lets the evaluation's ranking decide. After each kept box , every remaining box gets
and the next box is the highest updated score. Boxes whose score falls below a small floor (here 0.001) are dropped. A duplicate with IoU 0.9 is pushed far down the ranking; a neighbour with IoU 0.4 keeps most of its score and can still count as a true positive, after the true positives of the confident boxes. The same crowded scenes, greedy NMS against both Soft-NMS variants:
import numpy as np
def iou_matrix(a, b):
a, b = np.asarray(a, float)[:, None], np.asarray(b, float)[None]
iw = (np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0])).clip(0)
ih = (np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1])).clip(0)
area = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
return iw * ih / (area(a) + area(b) - iw * ih)
def nms(boxes, scores, thr):
order, keep = np.argsort(-scores, kind="stable"), []
while order.size:
i, order = order[0], order[1:]
keep.append(int(i))
order = order[iou_matrix(boxes[i:i + 1], boxes[order])[0] <= thr]
return boxes[keep], scores[keep]
def soft_nms(boxes, scores, method, thr=0.5, sigma=0.5, floor=0.001):
s, idx, out_b, out_s = scores.copy(), np.arange(len(scores)), [], []
while idx.size:
k = int(np.argmax(s[idx])); i = idx[k]
out_b.append(boxes[i]); out_s.append(s[i])
idx = np.delete(idx, k)
iou = iou_matrix(boxes[i:i + 1], boxes[idx])[0]
if method == "linear":
s[idx] *= np.where(iou > thr, 1 - iou, 1.0)
else:
s[idx] *= np.exp(-iou ** 2 / sigma)
idx = idx[s[idx] >= floor]
return np.array(out_b).reshape(-1, 4), np.array(out_s)
def crowd_scene(rng, n=6):
x = 20 + np.cumsum(rng.integers(8, 31, n)); y = rng.integers(20, 40, n)
gt = np.c_[x, y, x + 40, y + 100].astype(float)
boxes = np.repeat(gt, 6, axis=0) + rng.normal(0, 3, (6 * n, 4))
scores = rng.uniform(0.5, 0.95, 6 * n)
fa = rng.uniform(0, 300, (3, 2)); fa = np.c_[fa, fa + [40, 100]]
return gt, np.r_[boxes, fa], np.r_[scores, rng.uniform(0.05, 0.6, 3)]
def ap50(scenes, post):
rows, n_gt = [], 0
for gt, boxes, scores in scenes:
b, s = post(boxes, scores); used = set()
for k in np.argsort(-s, kind="stable"):
m = iou_matrix(b[k:k + 1], gt)[0]; j = int(m.argmax())
hit = m[j] >= 0.5 and j not in used
used |= {j} if hit else set(); rows.append((s[k], hit))
n_gt += len(gt)
rows.sort(key=lambda r: -r[0]); tp = np.array([r[1] for r in rows], float)
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / n_gt
return np.sum(np.diff(np.r_[0, rec]) * np.maximum.accumulate(prec[::-1])[::-1]), rec[-1]
rng = np.random.default_rng(0)
scenes = [crowd_scene(rng) for _ in range(100)]
for name, post in [("greedy NMS 0.5", lambda b, s: nms(b, s, 0.5)),
("Soft-NMS linear", lambda b, s: soft_nms(b, s, "linear")),
("Soft-NMS Gaussian", lambda b, s: soft_nms(b, s, "gaussian"))]:
ap, rec = ap50(scenes, post)
print(f"{name:18s} AP@0.5 {ap:.3f} max recall {rec:.3f}")
gt, b, s = scenes[0]
sb, ss = soft_nms(b, s, "gaussian")
print("scene 0, Gaussian Soft-NMS: boxes left", len(ss), "of", len(s), "| top 8 scores", ss[:8].round(2).tolist())greedy NMS 0.5 AP@0.5 0.923 max recall 0.923
Soft-NMS linear AP@0.5 0.978 max recall 1.000
Soft-NMS Gaussian AP@0.5 0.958 max recall 1.000
scene 0, Gaussian Soft-NMS: boxes left 25 of 39 | top 8 scores [0.95, 0.92, 0.83, 0.8, 0.49, 0.47, 0.36, 0.33]
Both variants beat greedy NMS at the same 0.5 threshold on these crowds (AP 0.978 linear, 0.958 Gaussian, against 0.923) and, because they never delete a box outright, they reach recall 1.000: every person is in the ranked list somewhere. In scene 0 the four confident people keep scores 0.80 to 0.95, while two overlapped people drop to 0.49 and 0.47, still above every duplicate. Soft-NMS is a drop-in change, needs no retraining and costs the same ; its drawback is more low-score boxes in the output, so the final score threshold matters more. Note that tuned greedy NMS (0.6, AP 0.976) does as well here: on real crowds the published gains of Soft-NMS were around 1 to 2 AP points on COCO.
The library versions agree
OpenCV ships NMS in its DNN module, so it runs in the browser. It takes boxes as [x, y, w, h] (convert first) plus a score threshold and the IoU threshold, and returns the kept indices, best first. Checked against the from-scratch version on 300 random boxes:
import numpy as np
import cv2
cv2.setLogLevel(0)
def iou_one_to_many(b, others):
iw = (np.minimum(b[2], others[:, 2]) - np.maximum(b[0], others[:, 0])).clip(0)
ih = (np.minimum(b[3], others[:, 3]) - np.maximum(b[1], others[:, 1])).clip(0)
area = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
return iw * ih / (area(b) + area(others) - iw * ih)
def nms(boxes, scores, thr):
order, keep = np.argsort(-scores, kind="stable"), []
while order.size:
i, order = order[0], order[1:]
keep.append(int(i))
order = order[iou_one_to_many(boxes[i], boxes[order]) <= thr]
return keep
rng = np.random.default_rng(0)
xy = rng.uniform(0, 400, (300, 2)); wh = rng.uniform(20, 120, (300, 2))
boxes = np.c_[xy, xy + wh]
scores = rng.uniform(0, 1, 300)
labels = rng.integers(0, 3, 300)
for thr in [0.3, 0.5, 0.7]:
ours = nms(boxes, scores, thr)
xywh = np.c_[boxes[:, :2], boxes[:, 2:] - boxes[:, :2]].tolist()
cv = cv2.dnn.NMSBoxes(xywh, scores.tolist(), 0.0, thr)
print(f"IoU {thr}: ours keeps {len(ours)}, OpenCV keeps {len(cv)}, same indices in the same order: {ours == np.ravel(cv).tolist()}")
cvb = cv2.dnn.NMSBoxesBatched(np.c_[boxes[:, :2], boxes[:, 2:] - boxes[:, :2]].tolist(), scores.tolist(), labels.tolist(), 0.0, 0.5)
ours_b = sorted(sum([np.flatnonzero(labels == c)[nms(boxes[labels == c], scores[labels == c], 0.5)].tolist() for c in range(3)], []))
print("class-aware: OpenCV NMSBoxesBatched keeps", len(cvb), "| per-class loop keeps", len(ours_b), "| same set:", sorted(np.ravel(cvb).tolist()) == ours_b)IoU 0.3: ours keeps 137, OpenCV keeps 137, same indices in the same order: True
IoU 0.5: ours keeps 240, OpenCV keeps 240, same indices in the same order: True
IoU 0.7: ours keeps 294, OpenCV keeps 294, same indices in the same order: True
class-aware: OpenCV NMSBoxesBatched keeps 277 | per-class loop keeps 277 | same set: True
In PyTorch the functions are torchvision.ops.nms and torchvision.ops.batched_nms (class-aware: it uses the offset trick for small inputs and a per-class loop for large ones). They take float tensors of [x1, y1, x2, y2] boxes, run on the GPU when the tensors are there, and are what torchvision's Faster R-CNN calls. This example needs PyTorch, so it is recorded (run in Docker on a CPU):
import numpy as np
import torch
from torchvision.ops import nms as tv_nms, batched_nms, box_iou
def iou_one_to_many(b, others):
iw = (np.minimum(b[2], others[:, 2]) - np.maximum(b[0], others[:, 0])).clip(0)
ih = (np.minimum(b[3], others[:, 3]) - np.maximum(b[1], others[:, 1])).clip(0)
area = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
return iw * ih / (area(b) + area(others) - iw * ih)
def nms(boxes, scores, thr):
order, keep = np.argsort(-scores, kind="stable"), []
while order.size:
i, order = order[0], order[1:]
keep.append(int(i))
order = order[iou_one_to_many(boxes[i], boxes[order]) <= thr]
return keep
rng = np.random.default_rng(0)
xy = rng.uniform(0, 400, (300, 2)); wh = rng.uniform(20, 120, (300, 2))
boxes = np.c_[xy, xy + wh]
scores = rng.uniform(0, 1, 300)
labels = rng.integers(0, 3, 300)
B, S, L = torch.tensor(boxes, dtype=torch.float64), torch.tensor(scores), torch.tensor(labels)
print("box_iou matches NumPy:", bool(np.allclose(box_iou(B[:5], B).numpy()[0], iou_one_to_many(boxes[0], boxes))))
for thr in [0.3, 0.5, 0.7]:
ours, tv = nms(boxes, scores, thr), tv_nms(B, S, thr).tolist()
print(f"IoU {thr}: ours keeps {len(ours)}, torchvision keeps {len(tv)}, identical: {ours == tv}")
tvb = batched_nms(B, S, L, 0.5).tolist()
ours_b = sorted(sum([np.flatnonzero(labels == c)[nms(boxes[labels == c], scores[labels == c], 0.5)].tolist() for c in range(3)], []), key=lambda i: -scores[i])
print("batched_nms keeps", len(tvb), "| per-class loop keeps", len(ours_b), "| identical:", tvb == ours_b)box_iou matches NumPy: True
IoU 0.3: ours keeps 137, torchvision keeps 137, identical: True
IoU 0.5: ours keeps 240, torchvision keeps 240, identical: True
IoU 0.7: ours keeps 294, torchvision keeps 294, identical: True
batched_nms keeps 277 | per-class loop keeps 277 | identical: True
All three implementations keep exactly the same boxes in the same order at every threshold, per class too. The one convention that could differ is a tie at exactly : these all remove a box only when IoU is strictly greater than the threshold.
Beyond hand-written NMS
NMS is a hand-written rule bolted onto a learned model, and a recent line of detectors removes it:
- DETR (2020) predicts a fixed set of, say, 100 boxes with a transformer and trains with a one-to-one (Hungarian) matching between predictions and objects, so the model itself learns not to produce duplicates.
- YOLOv10 (2024) trains one head with one-to-many assignment (rich signal) and a second head with one-to-one assignment, and uses only the second at inference: "NMS-free" YOLO.
- Crowd-specific fixes (adaptive NMS thresholds per box, predicting several boxes per candidate) target pedestrian data sets such as CrowdHuman.
For a classical anchor-based or anchor-free detector, including the YOLOv8 and YOLO11 used in this course, NMS is still part of inference, and its iou argument is one you will tune (Ultralytics YOLO).
Pitfalls
- Agnostic when it should be per class (and the reverse). Agnostic NMS deletes a rider's bicycle; per-class NMS keeps "cat" and "dog" on one animal. Decide from how classes overlap in your data.
- Wrong box format.
cv2.dnn.NMSBoxeswants[x, y, w, h], torchvision wants[x1, y1, x2, y2]. Passing corners to OpenCV gives an IoU on nonsense boxes and no error. - Comparing NMS settings with a score threshold in place. As with AP in general, evaluate with a low score threshold, then choose the operating threshold.
- A threshold copied from a paper. 0.45, 0.5, 0.6 and 0.7 are all common defaults; the right value depends on crowding. Tune it on validation data.
- NMS cost. with thousands of candidates per image can cost more than the network on a CPU. Pre-filter by score and cap the number of boxes (top-k) before NMS.
- Evaluating without NMS and wondering why precision is low. Duplicates are counted as false positives by every AP implementation.
Practice
- Three boxes with scores 0.9, 0.8 and 0.7. IoU(1, 2) = 0.6, IoU(1, 3) = 0.3, IoU(2, 3) = 0.6. Which boxes does greedy NMS keep at ?
Answer
Box 1 is kept and removes box 2 (0.6 > 0.5). Box 3 overlaps box 1 by only 0.3, so it is kept: boxes 1 and 3. Box 2 would have removed box 3, but box 2 is already gone; greedy NMS is order-dependent.
- With linear Soft-NMS (), what happens to the score of box 2 above after box 1 is kept?
Answer
. Box 3 (score 0.7) is now the highest, is kept next and lowers box 2 again: . Box 2 remains in the output with score 0.128, unless the final floor is higher.
- In the crowd example, which threshold would you choose for a pedestrian counter, and how would you check it?
Answer
A counter is hurt by both errors (a duplicate counts a person twice, a suppressed neighbour not at all), so pick the threshold that minimises duplicates plus missed people on a validation set that is as crowded as the deployment scenes: 0.6 in the simulated data (18 + 13 errors in 600). Then report the count error on a separate test set.
Test yourself
What does greedy NMS remove?
- All boxes below a score of 0.5
- Boxes that overlap a higher-scoring kept box by more than the IoU threshold
- Boxes of rare classes
- Boxes far from the image centre
In the simulated crowds, NMS at IoU 0.3 lost 174 of 600 people. Why?
- The detector missed them
- Neighbouring people overlap with IoU above 0.3, so the less confident one was suppressed as a duplicate
- The score threshold was too high
- Soft-NMS was used
Why is the class-offset trick in batched NMS exact?
- It averages the boxes of each class
- Shifting each class far enough apart makes IoU between classes zero, so one NMS call equals a loop over classes
- It uses a different IoU threshold per class
- It sorts by class first
How does Soft-NMS differ from greedy NMS?
- It uses a lower IoU threshold
- It lowers the scores of overlapping boxes instead of deleting them
- It needs retraining
- It only works for one class