非极大值抑制(NMS,Non-Maximum Suppression)的原理与代码详解
时间:2019-03-01 00:05:14
收藏:0
阅读:1101
1、NMS的原理
NMS(Non-Maximum Suppression)算法在目标检测算法中得到广泛应用,本质是搜索局部极大值,抑制非极大值元素。NMS就是需要根据score矩阵和region的坐标信息,从中找到置信度比较高的bounding box。首先,根据score进行排序,然后计算出每一个bounding box的面积,把score最大的bounding box作为队列中。接下来,计算其余bounding box与当前最大score与box的IoU,去除IoU大于设定的阈值的bounding box。然后重复上面的过程,直至候选bounding box为空。最终,检测了bounding box的过程中有两个阈值,一个就是IoU,另一个是在过程之后,从候选的bounding box中剔除score小于阈值的bounding box。需要注意的是:Non-Maximum Suppression一次处理一个类别,如果有N个类别,Non-Maximum Suppression就需要执行N次。
2、NMS的实现代码详解(来自Fast-RCNN)
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import numpy as np def py_cpu_nms(dets, thresh): """Pure Python NMS baseline.""" 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] #[::-1]表示降序排序,输出为其对应序号 keep = [] #需要保留的bounding box while order.size > 0: i = order[0] #取置信度最大的(即第一个)框 keep.append(i) #将其作为保留的框 #以下计算置信度最大的框(order[0])与其它所有的框(order[1:],即第二到最后一个)框的IOU,以下都是以向量形式表示和计算 xx1 = np.maximum(x1[i], x1[order[1:]]) #计算xmin的max,即overlap的xmin yy1 = np.maximum(y1[i], y1[order[1:]]) #计算ymin的max,即overlap的ymin xx2 = np.minimum(x2[i], x2[order[1:]]) #计算xmax的min,即overlap的xmax yy2 = np.minimum(y2[i], y2[order[1:]]) #计算ymax的min,即overlap的ymax w = np.maximum(0.0, xx2 - xx1 + 1) #计算overlap的width h = np.maximum(0.0, yy2 - yy1 + 1) #计算overlap的hight inter = w * h #计算overlap的面积 ovr = inter / (areas[i] + areas[order[1:]] - inter) #计算并,-inter是因为交集部分加了两次。 inds = np.where(ovr <= thresh)[0] #本轮,order仅保留IOU不大于阈值的下标 order = order[inds + 1] #删除IOU大于阈值的框 return keep
原文:https://www.cnblogs.com/houjun/p/10454117.html
评论(0)