非极大值抑制(Non-Maximum Suppression NMS)
NMS就是去除冗余的检测框,保留最好的一个。
产生proposal后使用分类网络给出每个框的每类置信度,使用回归网络修正位置,最终应用NMS.
对于Bounding Box的列表B及其对应的置信度S,采用下面的计算方式.选择具有最大score的检测框M,将其从B集合中移除并加入到最终的检测结果D中.通常将B中剩余检测框中与M的IoU大于阈值Nt的框从B中移除.重复这个过程,直到B为空.
参考: http://www.cnblogs.com/makefile/p/nms.html © 康行天下
1 def nms_cpu(dets, thresh): 2 dets = dets.numpy() 3 #x1、y1、x2、y2、以及score赋值 4 x1 = dets[:, 0] 5 y1 = dets[:, 1] 6 x2 = dets[:, 2] 7 y2 = dets[:, 3] 8 scores = dets[:, 4] 9 10 ##每一个检测框的面积 11 areas = (x2 - x1 + 1) * (y2 - y1 + 1) 12 #按照score置信度降序排序 13 order = scores.argsort()[::-1]#argsort函数返回的是数组值从小到大的索引值,然后又降序 14 15 keep = []#保留的结果框集合 16 while order.size > 0: 17 i = order.item(0) 18 keep.append(i)#保留该类剩余box中得分最高的一个 19 #得到相交区域,左上及右下########## 20 xx1 = np.maximum(x1[i], x1[order[1:]])#X 与 Y 逐位比较取其大者 21 yy1 = np.maximum(y1[i], y1[order[1:]]) 22 xx2 = np.minimum(x2[i], x2[order[1:]]) 23 yy2 = np.minimum(y2[i], y2[order[1:]]) 24 25 ##计算相交的面积,不重叠时面积为0 26 w = np.maximum(0.0, xx2 - xx1 + 1) 27 h = np.maximum(0.0, yy2 - yy1 + 1) 28 inter = w * h 29 #计算IoU:重叠面积 /(面积1+面积2-重叠面积) 30 ovr = inter / (areas[i] + areas[order[1:]] - inter) 31 32 ##保留IoU小于阈值的box 33 ##只有条件 (condition),没有x和y,则输出满足条件 (即非0) 元素的坐标 (等价于numpy.nonzero)。 34 inds = np.where(ovr <= thresh)[0] 35 order = order[inds + 1]#因为ovr数组的长度比order数组少一个,所以这里要将所有下标后移一位 36 37 return torch.IntTensor(keep)
ref:https://blog.csdn.net/weixin_43872578/article/details/87909640