Coding中等
手撕 NMS(非极大值抑制)
排序 + 贪心 + IoU 过滤;
简要回答
排序 + 贪心 + IoU 过滤;soft-NMS 按 IoU 衰减而非删;多类应分类做。
标准答案
考察点:排序 + 贪心 + IoU 过滤;soft-NMS 按 IoU 衰减而非删;多类应分类做。
实现:
import numpy as npdef nms(boxes, scores, iou_thresh=0.5):
# boxes: [N, 4] (x1,y1,x2,y2);scores: [N]
order = scores.argsort()[::-1] # 按 score 降序索引
keep = []
x1, y1 = boxes[:, 0], boxes[:, 1]
x2, y2 = boxes[:, 2], boxes[:, 3]
areas = (x2 - x1) * (y2 - y1)
while order.size > 0:
i = order[0]
keep.append(i)
# 当前框与剩余框做向量化 IoU
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
inter = np.clip(xx2 - xx1, 0, None) * np.clip(yy2 - yy1, 0, None)
iou = inter / (areas[i] + areas[order[1:]] - inter + 1e-6)
# 保留 iou <= thresh 的;+1 因为 order[0] 已剔除
order = order[1:][iou <= iou_thresh]
return keep
常见错误
- 未按类别分别 NMS(不同类不该互抑)
- 忘 score thresh 预过滤 → N 大 TLE
- 取 1.0 等于不抑制。