1. 算法原理
非極大值抑制算法(Non-maximum suppression, NMS)的本質是搜索局部極大值,抑制非極大值元素。
2. 3鄰域情況下NMS的實現
3鄰域情況下的NMS即判斷一維數組I[W]的元素I[i](2<=i<=W-1)是否大於其左鄰元素I[i-1]和右鄰元素I[i+1],算法流程如下圖所示:

a. 算法流程3-5行判斷當前元素是否大於其左鄰與右鄰元素,如符合條件,該元素即為極大值點。對於極大值點I[i],已知I[i]>I[i+1],故無需對i+1位置元素做進一步處理,直接跳至i+2位置,對應算法流程第12行。

b. 若元素I[i]不滿足算法流程第3行判斷條件,將其右鄰I[i+1]作為極大值候選,對應算法流程第7行。采用單調遞增的方式向右查找,直至找到滿足I[i]>I[i+1]的元素,若i<=W-1,該點即為極大值點,對應算法流程第10-11行。

3. NMS在物體檢測中的應用
物體檢測中應用NMS算法的主要目的是消除多余(交叉重復)的窗口,找到最佳物體檢測位置。


如上圖所示,人臉檢測中,雖然每個窗口均檢測到人臉,但僅需給出一個最有可能表征人臉的窗口。
4. 算法程序
function pickLocate = nms(boxes, overlap)
% Non-maximum suppression.
% In object detect algorithm, select high score detections and skip windows
% covered by a previously selected detection.
%
% input - boxes : object detect windows.
% xMin yMin xMax yMax score.
% overlap : suppression threshold.
% output - pickLocate : number of local maximum score.
boxes = double(boxes);
if isempty(boxes)
pickLocate = [];
else
xMin = boxes(:, 1);
yMin = boxes(:, 2);
xMax = boxes(:, 3);
yMax = boxes(:, 4);
s = boxes(:, end);
% area of every detected windows.
area = (xMax - xMin + 1) .* (yMax - yMin + 1);
% sort detected windows based on the score.
[vals, I] = sort(s);
pickLocate = [];
while ~isempty(I)
last = length(I);
i = I(last);
pickLocate = [pickLocate; i];
suppress = [last];
for pos = 1 : last - 1
j = I(pos);
% covered area.
xx1 = max(xMin(i), xMin(j));
yy1 = max(yMin(i), yMin(j));
xx2 = min(xMax(i), xMax(j));
yy2 = min(yMax(i), yMax(j));
w = xx2 - xx1 + 1;
h = yy2 - yy1 + 1;
if ((w > 0) && (h > 0))
% compute overlap.
o = w * h / min(area(i), area(j));
if (o > overlap)
suppress = [suppress; pos];
end
end
% xx1 = max(x1(i), x1(I(1:last-1)));
% yy1 = max(y1(i), y1(I(1:last-1)));
% xx2 = min(x2(i), x2(I(1:last-1)));
% yy2 = min(y2(i), y2(I(1:last-1)));
% w = max(0.0, xx2-xx1+1);
% h = max(0.0, yy2-yy1+1);
% inter = w.*h;
% o = inter ./ (area(i) + area(I(1:last-1)) - inter);
% saving the windows which o less than threshold.
% I = I(o <= overlap);
end
I(suppress) = [];
end
end
