Day 48: Non-max suppression: the algorithm
From many boxes to one per object
A detector outputs dozens of overlapping boxes for each real object. Non-maximum suppression (NMS) cleans this up: keep the highest-confidence box, remove every other box that overlaps it too much, repeat. You met the name in Stage 0 Day 9 (thinning edge responses); here it's the same idea applied to bounding boxes. Overlap is measured by IoU β intersection over union.
IoU and the NMS loop
IoU = area of overlap / area of union of two boxes, from 0 (no overlap) to 1 (identical). NMS sorts boxes by confidence, takes the top one as a keeper, discards any remaining box whose IoU with the keeper exceeds a threshold (say 0.5), and repeats on what's left. The threshold trades duplicates against merged-but-distinct objects.
def nms(boxes, scores, iou_threshold=0.5):
keep = []
order = scores.argsort()[::-1] # highest score first
while len(order) > 0:
i = order[0]
keep.append(i)
rest = order[1:]
ious = np.array([iou(boxes[i], boxes[j]) for j in rest])
order = rest[ious < iou_threshold] # drop boxes overlapping the keeper
return keepIoU is a metric you'll reuse
IoU shows up again as the standard evaluation metric for segmentation (Day 67) β 'how well does the predicted mask overlap the true mask?'. Learn it as *the* measure of spatial agreement between two regions and it pays off repeatedly across this stage.
Key terms
- Non-maximum suppression (NMS)
- Reducing many overlapping detection boxes to one per object by iteratively keeping the highest-confidence box and removing those overlapping it.
- IoU (Intersection over Union)
- Overlap area divided by union area of two boxes/regions; 0 = disjoint, 1 = identical.
In NMS, what happens to a lower-confidence box whose IoU with a kept higher-confidence box exceeds the threshold?