【NMS】-非极大值抑制
nms 算法过程
- 将所有框的得分排序,选中最高分及其对应的框
- 遍历其余的框,如果和当前最高分框的重叠面积(IOU)大于一定阈值,我们将框删除
- 从未处理的框中继续选一个得分最高的,重复上述过程
'''
比如:A、B、C、D、E、F、G、H、I、J
假设 A 的得分最高,IOU>0.7,剔除
1. 计算与A的 IOU, 若 BEG(和A的IOU) > 0.7 , 剔除 BEG
2. 若剩下 C、D、F、H、I、J 中F得分最高,计算和F的IOU DHI > 0.7 剔除
3. 若 C、J 中C得分最高,J与C计算IOU,若结果>0.7 剔除J
输出3个目标 A/F/C
'''
'''
1. 计算候选框的面积时加1?
候选框面积算的是像素点数,比如候选框左上和右下点坐标相同时,面积应该为1,如果计算面积时不+1,候选框面积就变成0了
'''
import numpy as np
def py_nms(dets, thresh):
'''
Pure Python NMS baseline
@ dets = [x1,y1,x2,y2,scores]
@ thresh 阈值
'''
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
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:]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= thresh)[0]
'''将order序列更新,由于前面得到的矩形框索引要比矩形框在原order序列中的索引小1,所以要把这个1加回来'''
order = order[inds + 1]
return keep
if __name__ == "__main__":
dets = np.array([[30, 20, 230, 200, 1],
[50, 50, 260, 220, 0.9],
[210, 30, 420, 5, 0.8],
[430, 280, 460, 360, 0.7]])
thresh = 0.35
keep_dets = py_nms(dets, thresh)
print(keep_dets)
print(dets[keep_dets])
[0, 2, 3]
[[ 30. 20. 230. 200. 1. ]
[ 210. 30. 420. 5. 0.8]
[ 430. 280. 460. 360. 0.7]]