什么是NMS
NMS,是Non Maximum Suppression
的缩写,中文翻译过来就是非极大值抑制,是目标检测算法中的后期处理模块,它的主要作用是删除高度冗余的bounding box
。
下图显示了NMS
的工作机制
在目标检测过程中,算法对于每个目标(object
)在检测的时候都会产生很多个bounding box
,通过NMS
,就能够去除冗余,得到最终的结果。
NMS的基本步骤
- 将所有检出的
output bounding box
按每个类别(class
)的得分(score
)划分,将每个类别的score
作为一个集合 -
遍历每个集合,对每个集合进行如下计算
NMS的代码实现
下面的这份NMS
实现,来自Fast R-CNN
,大家可以参考参考
# --------------------------------------------------------
# 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] # pred bbox top_x
y1 = dets[:, 1] # pred bbox top_y
x2 = dets[:, 2] # pred bbox bottom_x
y2 = dets[:, 3] # pred bbox bottom_y
scores = dets[:, 4] # pred bbox cls score
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
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 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= thresh)[0]
order = order[inds + 1]
return keep