#242 · Computer Vision · Hard
⊣ Solve on deep-ml.comImplement Non-Maximum Suppression (NMS) for object detection. Given a set of bounding boxes with confidence scores, remove overlapping boxes that likely refer to the same object.
def nms(
boxes: list[list[float]],
scores: list[float],
iou_threshold: float = 0.5,
) -> list[int]:
"""
boxes: [[x1, y1, x2, y2], ...] bounding box coordinates
scores: confidence score for each box
Returns: indices of boxes to keep
"""
if not boxes:
return []
n = len(boxes)
indices = sorted(range(n), key=lambda i: scores[i], reverse=True)
def compute_iou(i, j):
x1 = max(boxes[i][0], boxes[j][0])
y1 = max(boxes[i][1], boxes[j][1])
x2 = min(boxes[i][2], boxes[j][2])
y2 = min(boxes[i][3], boxes[j][3])
inter_w = max(0, x2 - x1)
inter_h = max(0, y2 - y1)
intersection = inter_w * inter_h
area_i = (boxes[i][2] - boxes[i][0]) * (boxes[i][3] - boxes[i][1])
area_j = (boxes[j][2] - boxes[j][0]) * (boxes[j][3] - boxes[j][1])
union = area_i + area_j - intersection
if union <= 0:
return 0.0
return intersection / union
keep = []
suppressed = set()
for idx in indices:
if idx in suppressed:
continue
keep.append(idx)
for other in indices:
if other in suppressed or other == idx:
continue
if compute_iou(idx, other) > iou_threshold:
suppressed.add(other)
return keep