SDE & MLE Prep

IoU & Non-Maximum Suppression

Key idea: IoU = intersection area / union area of two boxes (clip negative overlaps to 0). NMS keeps the highest-scoring box, drops every remaining box whose IoU with it exceeds a threshold, and repeats — removing duplicate detections of the same object.

import numpy as np

def iou(box, boxes):                      # box: (4,), boxes: (N, 4) as x1, y1, x2, y2
    x1 = np.maximum(box[0], boxes[:, 0]); y1 = np.maximum(box[1], boxes[:, 1])
    x2 = np.minimum(box[2], boxes[:, 2]); y2 = np.minimum(box[3], boxes[:, 3])
    inter = np.clip(x2 - x1, 0, None) * np.clip(y2 - y1, 0, None)
    area = lambda b: (b[..., 2] - b[..., 0]) * (b[..., 3] - b[..., 1])
    return inter / (area(box) + area(boxes) - inter)

def nms(boxes, scores, thresh=0.5):
    order = np.argsort(-scores)           # best first
    keep = []
    while order.size:
        i = order[0]
        keep.append(int(i))
        rest = order[1:]
        order = rest[iou(boxes[i], boxes[rest]) <= thresh]
    return keep

boxes = np.array([[0, 0, 10, 10], [1, 1, 11, 11], [20, 20, 30, 30], [21, 21, 29, 29], [0, 0, 10, 10.5]], float)
scores = np.array([0.9, 0.8, 0.75, 0.7, 0.6])
assert np.isclose(iou(boxes[0], boxes[1:2])[0], 81 / 119)      # 9x9 overlap / (100 + 100 - 81)
assert iou(boxes[0], boxes[2:3])[0] == 0
assert nms(boxes, scores, 0.5) == [0, 2]
print("ok", nms(boxes, scores, 0.5))

Follow-ups: soft-NMS (decay scores instead of deleting), class-wise NMS, and why DETR-style detectors don't need NMS (set prediction with Hungarian matching).