【代碼】NMS

# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------

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)
    order = scores.argsort()[::-1]

    keep = []
    while order.size > 0:
        i = order[0]
        keep.append(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]

    return keep

以上爲代碼。下面說說它是怎麼來的。

假設det1爲[a1, b1, a2, b2], det2爲[x1, y1, x2, y2],我們要求他們的交和並。

det1的集合表示爲{(x, y) | a1 < x < a2, b1 < y < b2},det2 = {(x, y) | x1 < x < x2, y1 < y < y2}

求交

求兩個集合的交Int = {(x, y) | a1 < x < a2 且 b1 < y < b2 x1 < x < x2 且 y1 < y < y2} 

                            = {(x, y) | a1 < x < a2 且 x1 < x < x2 b1 < y < b2 且 y1 < y < y2} 

                            = {(x, y) | max(a1, x1) < x < min(a2, x2), max(b1, y1) < y < min(b2, y2)} 

其中要注意的是可能會出現max(a1, x1) > min(a2, x2)這種情況出現,這時Int爲空集。

求並

兩個集合的並不一定是矩形,但面積可以通過交來算出來

NMS

keep=[] 
score降序排列
    while(score不爲空)
        A = score最大的det
        將其餘det與A計算IOU
        刪除IOU過小的det
        score中刪除A
        keep中添加A
返回keep

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章