1. NMS
非极大抑制,筛选候选区域,删除冗余的候选框。
迭代过程:
对于某个类别中Bounding Box的位置以及置信度集合列表B,选择具有最大score的检测框M,将其从B集合中移除并加入到最终的 模型输出检测结果G中。然后将B中剩余检测框中与M的IoU大于阈值threshold的框从B中移除。然后重复上述过程,直到B为空。
import numpy as np
def nms(dets, thresh):
"""
dets: 检测的boxes以及对应的scores
thresh: 设定的阈值
"""
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:,4]
# 计算每个boxes的面积
areas = (x2 - x1)*(y2 - y1)
# 对分数进行排序,得到排序后的索引值的排序
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
#计算剩余boxes与当前box的重叠程度,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:]])
w = np.maximum(0.0, xx2 - xx1)
h = np.maximum(0.0, yy2 - yy1)
inter = w * h
ovr = inter/(areas[i]+areas[order[1:]]-inter)
# 保留iou小雨设定阈值的boxes
inds = np.where(ovr<=thresh)[0]
order = order[inds+1]
return keep