目标检测的非最大值抑制-NMS
Posted 刘二毛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了目标检测的非最大值抑制-NMS相关的知识,希望对你有一定的参考价值。
object detection[NMS][非极大抑制]
非极大抑制,是在对象检测中用的较为频繁的方法,当在一个对象区域,框出了很多框,那么如下图:
目的就是为了在这些框中找到最适合的那个框,主要就是通过迭代的形式,不断的以最大得分的框去与其他框做iou操作,并过滤那些iou较大(即交集较大)的框
按照github上R-CNN的 matlab代码,改成py的,具体如下:
def iou(xminNp,yminNp,xmaxNp,ymaxNp,areas,lastInd,beforeInd,threshold):
#将lastInd指向的box,与之前的所有存活的box指向坐标做比较
xminNpTmp = np.maximum(xminNp[lastInd], xminNp[beforeInd])
yminNpTmp = np.maximum(yminNp[lastInd], yminNp[beforeInd])
xmaxNpTmp = np.maximum(xmaxNp[lastInd], xmaxNp[beforeInd])
ymaxNpTmp = np.maximum(ymaxNp[lastInd], ymaxNp[beforeInd])
#计算lastInd指向的box,与存活box交集的,所有width,height
w = np.maximum(0.0,xmaxNpTmp-xminNpTmp)
h = np.maximum(0.0,ymaxNpTmp-yminNpTmp)
#计算存活box与last指向box的交集面积
inter = w*h
iouValue = inter/(areas[beforeInd]+areas[lastInd]-inter)
indexOutput = [item[0] for item in zip(beforeInd,iouValue) if item[1] <= threshold ]
return indexOutput
def nms(boxes,threshold):
'''
boxes:n by 5的矩阵,n表示box个数,每一行分别为[xmin,ymin,xmax,ymax,score]
'''
assert isinstance(boxes,numpy.ndarray),'boxes must numpy object'
assert boxes.shape[1] == 5,'the column Dimension should be 5'
xminNp = boxes[:,0]
yminNp = boxes[:,1]
xmaxNp = boxes[:,2]
ymaxNp = boxes[:,3]
scores = boxes[:,4]
#计算每个box的面积
areas = (xmaxNp-xminNp)*(ymaxNp-yminNp)
#对每个box的得分按升序排序
scoresSorted = sorted(list(enumerate(scores)),key = lambda item:item[1])
#提取排序后数据的原索引
index = [ item[0] for item in scoresSorted ]
pick = []
while index:
#将当前index中最后一个加入pick
lastInd = index[-1]
pick.append(lastInd)
#计算最后一个box与之前所有box的iou
index = iou(xminNp,yminNp,xmaxNp,ymaxNp,areas,lastInd,index[:-1],threshold)
return pick[:-1]
if __name__ == '__main__':
nms(boxes,threshold)
参考资料:
[] 非极大抑制。http://www.cnblogs.com/liekkas0626/p/5219244.html
以上是关于目标检测的非最大值抑制-NMS的主要内容,如果未能解决你的问题,请参考以下文章