非极大值抑制NMS算法
nms算法在目标检测算法中应用普遍,其主要的作用是去除检测到的多个目标框,进而确定最优的目标框。
原理:核心思想是对多个目标框进的置信度进行排序,选择最优置信度的框,然后设置一个阈值,当其他框与最优置信度框重合程度超过阈值时将其他框舍去,再在剩下的框中迭代重复该操作。
python代码
import numpy as np
dets = np.array([
[204, 102, 358, 250, 0.5],
[257, 118, 380, 250, 0.7],
[280, 135, 400, 250, 0.6],
[255, 118, 360, 235, 0.7]])
thresh = 0.3
该二维数组的构成[xmin, ymin, xmax, ymax, confidence]
nms.py
import numpy as np
def py_cpu_nms(dets, thresh):
'''Pure python NMS baseline'''
x1 = dets[:, 0] #xmin
y1 = dets[:, 1] #ymin
x2 = dets[:, 2] #xmax
y2 = dets[:, 3] #ymax
scores = dets[:, 4] #confidence
areas = (x2 - x1 + 1) * (y2 - y1 + 1) # size of bbox
order = scores.argsort()[:: -1] #descend sort bbox scores
keep = []
while order.size >0:
i =order[0] # highest score of bbox confidence
keep.append(i)
xx1=np.maximun(x1[i], x1[order[1:]])
yy1=np.maxiumun(y1[i], y1[order[1:]])
xx2=np.minimun(x2[i], x2[order[1:]])
yy2=np.minimun(y2[i], y2[order[1:]])
w =np.maximun(0.0, xx2 - xx1 +1)
h =np.maximun(0.0, yy2-yy1 +1)
inter = w*h
ovr = inter / (area[i] + areas[order[i:]] - inter)
inds=np.where(ovr<=thres[0])
order = order[inds +1]
return keep