非極大值抑制(NMS,Non-Maximum Suppression)的原理與代碼詳解

一、NMS的原理

NMS(Non-Maximum Suppression)算法本質是搜索局部極大值,抑制非極大值元素。NMS就是須要根據score矩陣和region的座標信息,從中找到置信度比較高的bounding box。NMS是大部分深度學習目標檢測網絡所須要的,大體算法流程爲:算法

1.對全部預測框的置信度降序排序網絡

2.選出置信度最高的預測框,確認其爲正確預測,並計算他與其餘預測框的IOUapp

3.根據2中計算的IOU去除重疊度高的,IOU>threshold就刪除學習

4.剩下的預測框返回第1步,直到沒有剩下的爲止spa

須要注意的是:Non-Maximum Suppression一次處理一個類別,若是有N個類別,Non-Maximum Suppression就須要執行N次。code

二、NMS的實現代碼詳解(來自Fast-RCNN)

# --------------------------------------------------------
# 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]  #[::-1]表示降序排序,輸出爲其對應序號

    keep = []                     #須要保留的bounding box
    while order.size > 0:
        i = order[0]              #取置信度最大的(即第一個)框
        keep.append(i)            #將其做爲保留的框
        
        #如下計算置信度最大的框(order[0])與其它全部的框(order[1:],即第二到最後一個)框的IOU,如下都是以向量形式表示和計算
        xx1 = np.maximum(x1[i], x1[order[1:]]) #計算xmin的max,即overlap的xmin
        yy1 = np.maximum(y1[i], y1[order[1:]]) #計算ymin的max,即overlap的ymin
        xx2 = np.minimum(x2[i], x2[order[1:]]) #計算xmax的min,即overlap的xmax
        yy2 = np.minimum(y2[i], y2[order[1:]]) #計算ymax的min,即overlap的ymax

        w = np.maximum(0.0, xx2 - xx1 + 1)      #計算overlap的width
        h = np.maximum(0.0, yy2 - yy1 + 1)      #計算overlap的hight
        inter = w * h                           #計算overlap的面積
        ovr = inter / (areas[i] + areas[order[1:]] - inter) #計算並,-inter是由於交集部分加了兩次。

        inds = np.where(ovr <= thresh)[0]          #本輪,order僅保留IOU不大於閾值的下標
        order = order[inds + 1]                    #刪除IOU大於閾值的框

    return keep   
相關文章
相關標籤/搜索