tensorflow学习——NMS的python实现

1、NMS(Non-Maximum Suppression)
根据框的概率和IOU进行抑制

import numpy as np  

def py_cpu_nms(dets, thresh):  
    """Pure Python NMS baseline."""  
    x1 = dets[:, 0]  
    y1 = dets[:, 1]  
    x2 = dets[:, 2]  
    y2 = dets[:, 3]  
    scores = dets[:, 4]  

    areas = (x2 - x1 + 1) * (y2 - y1 + 1)  
#从大到小排列,取index  
    order = scores.argsort()[::-1]  
#keep为最后保留的边框  
    keep = []  
    while order.size > 0:  
#order[0]是当前分数最大的窗口,之前没有被过滤掉,肯定是要保留的  
        i = order[0]  
        keep.append(i)  
#计算窗口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  
#交/并得到iou值  
        ovr = inter / (areas[i] + areas[order[1:]] - inter)  
#ind为所有与窗口i的iou值小于threshold值的窗口的index,其他窗口此次都被窗口i吸收  
        inds = np.where(ovr <= thresh)[0]  
#下一次计算前要把窗口i去除,所有i对应的在order里的位置是0,所以剩下的加1  
        order = order[inds + 1]  
    return keep

def main():
    x = np.array([[3,6,9,11,0.9],[6,3,8,7,0.6],[3,7,10,12,0.7],[1,4,13,7,0.2]])
    y = py_cpu_nms(x, 0.3)
if __name__ == '__main__':
    main()

2、转自网上教程
首先比较二者的参数部分:

np.max:(a, axis=None, out=None, keepdims=False)
    求序列的最值
    最少接收一个参数
    axis:默认为列向(也即 axis=0),axis = 1 时为行方向的最值;
np.maximum:(X, Y, out=None)
    X 与 Y 逐位比较取其大者;
    最少接收两个参数
>> np.max([-2, -1, 0, 1, 2])
2

>> np.maximum([-2, -1, 0, 1, 2], 0)
array([0, 0, 0, 1, 2])

        # 当然 np.maximum 接受的两个参数,也可以大小一致
        # 或者更为准确地说,第二个参数只是一个单独的值时,其实是用到了维度的 broadcast 机制;

3、计算IOU

def calcIOU(x1, y1, w1, h1, x2, y2, w2, h2):
    if((abs(x1 - x2) < ((w1 + w2)/ 2.0)) and (abs(y1-y2) < ((h1 + h2)/2.0))):
        left = max((x1 - (w1 / 2.0)), (x2 - (w2 / 2.0)))
        upper = max((y1 - (h1 / 2.0)), (y2 - (h2 / 2.0)))

        right = min((x1 + (w1 / 2.0)), (x2 + (w2 / 2.0)))
        bottom = min((y1 + (h1 / 2.0)), (y2 + (h2 / 2.0)))

        inter_w = abs(left - right)
        inter_h = abs(upper - bottom)
        inter_square = inter_w * inter_h
        union_square = (w1 * h1)+(w2 * h2)-inter_square

        calcIOU = inter_square/union_square * 1.0
        print("calcIOU:", calcIOU)
    else:
        print("No intersection!")

    return calcIOU
def main():
    calcIOU(1, 2, 2, 2, 2, 1, 2, 2)

if __name__ == '__main__':
    main()

你可能感兴趣的:(tensorflow学习——NMS的python实现)