NMS python實現


import numpy as np

'''
目標檢測中常用到NMS,在faster R-CNN中,每一個bounding box都有一個打分,NMS實現邏輯是:

    1,按打分最高到最低將BBox排序 ,例如:A B C D E F

    2,A的分數最高,保留。從B-E與A分別求重疊率IoU,假設B、D與A的IoU大於閾值,那么B和D可以認為是重復標記去除

    3,余下C E F,重復前面兩步。

'''
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]  # bbox打分

    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 = max(x1[i], x1[order[1:]])
        yy1 = max(y1[i], y1[order[1:]])
        xx2 = min(x2[i], x2[order[1:]])
        yy2 = min(y2[i], y2[order[1:]])

        w = max(0.0, xx2 - xx1 + 1)
        h = max(0.0, yy2 - yy1 + 1)
        inter = w * h
        # 交/並得到iou值
        ovr = inter / (areas[i] + areas[order[1:]] - inter)
        # inds為所有與窗口i的iou值小於threshold值的窗口的index,其他窗口此次都被窗口i吸收
        inds = np.where(ovr <= thresh)[0]
        # order里面只保留與窗口i交疊面積小於threshold的那些窗口,由於ovr長度比order長度少1(不包含i),所以inds+1對應到保留的窗口
        print('inds',inds,inds+1)
        order = order[inds + 1]  # inds 的第一個索引對應order的第二個索引

    return keep


if __name__=='__main__':
    print(py_cpu_nms(np.array([[661, 27, 679, 47, 0.8], [662, 27, 682, 47, 0.9]]),0.83))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM