以下圖爲例,由於滑動窗口,同一個人可能有好幾個框(每一個框都帶有一個分類器得分)
而我們的目標是一個人只保留一個最優的框:
於是我們就要用到非極大值抑制,來抑制那些冗餘的框: 抑制的過程是一個迭代-遍歷-消除的過程。
(1)將所有框的得分排序,選中最高分及其對應的框:
(2)遍歷其餘的框,如果和當前最高分框的重疊面積(IOU)大於一定閾值,我們就將框刪除。
(3)從未處理的框中繼續選一個得分最高的,重複上述過程。
Python 代碼:
# python3
import numpy as np
def py_nms(dets, thresh):
"""Pure Python NMS baseline."""
#x1、y1、x2、y2、以及score賦值
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
#每一個候選框的面積
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
#order是按照score降序排序的
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
#計算當前概率最大矩形框與其他矩形框的相交框的座標,會用到numpy的broadcast機制,得到的是向量
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或h算出來會是負數,用0代替
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
#計算重疊度IOU:重疊面積/(面積1+面積2-重疊面積)
ovr = inter / (areas[i] + areas[order[1:]] - inter)
#找到重疊度不高於閾值的矩形框索引
inds = np.where(ovr <= thresh)[0]
#將order序列更新,由於前面得到的矩形框索引要比矩形框在原order序列中的索引小1,所以要把這個1加回來
order = order[inds + 1]
return keep
# test
if __name__ == "__main__":
dets = np.array([[30, 20, 230, 200, 1],
[50, 50, 260, 220, 0.9],
[210, 30, 420, 5, 0.8],
[430, 280, 460, 360, 0.7]])
thresh = 0.35
keep_dets = py_nms(dets, thresh)
print(keep_dets)
print(dets[keep_dets])
---------------------
作者:Blateyang
來源:CSDN
原文:https://blog.csdn.net/Blateyang/article/details/79113030
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!
---------------------
作者:shuzfan
來源:CSDN
原文:https://blog.csdn.net/shuzfan/article/details/52711706
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!