参考博客:https://blog.youkuaiyun.com/hongxingabc/article/details/78996407
import numpy as np
thresh = 0.6 #设置阈值
nums = np.array([[100,100,200,200,0.8],
[300,300,400,400,0.75],
[101,101,202,202,0.78],
[135,135,345,345,0.65],
[400,230,567,345,0.9],
[12,12,98,98,0.9]]) #建立数组
x1 = nums[:, 0] #得到所有边框的第一个点的x坐标
y1 = nums[:, 1]
x2 = nums[:, 2]
y2 = nums[:, 3]
scores = nums[:, 4] #得到所有边框的置信度分数
areas = (x2 - x1 + 1) * (y2 - y1 + 1) #得到每个边框的面积
order = scores.argsort()[::-1] #分数从大到小排列,取index
keep = [] #keep为最后保留的边框
while order.size > 0:
i = order[0] #order[0]是当前分数最大的窗口,肯定保留
keep.append(nums[i]) #将窗口存入keep
#计算窗口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] #因为前面计算面积时用的order[1:],所以需要+1。
print(keep)