NMS的各种实现和速度对比

非极大值抑制(NMS)的几种实现

非极大值抑制(Non-Maximum Suppression,NMS) : python 代码实现和详细讲解

用matplotlib.pyplot 画 bounding box:
https://www.jianshu.com/p/8d14238d402a

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May  7 21:45:37 2018

@author: lps
"""
import numpy as np
import os
os.environ["DISPLAY"] = 'localhost:11.0'

boxes=np.array([[100,100,210,210,0.72],
        [250,250,420,420,0.8],
        [220,220,320,330,0.92],
        [100,100,210,210,0.72],
        [230,240,325,330,0.81],
        [220,230,315,340,0.9]]) 


def py_cpu_nms(dets, thresh):
    # dets:(m,5)  thresh:scaler
    
    x1 = dets[:,0]
    y1 = dets[:,1]
    x2 = dets[:,2]
    y2 = dets[:,3]
    
    areas = (y2-y1+1) * (x2-x1+1)
    scores = dets[:,4]
    keep = []
    
    index = scores.argsort()[::-1]  # 这里面存储着 分数按照降序排列的 所有框的 索引
    
    while index.size >0:

        i = index[0]       # every time the first is the biggst, and add it directly
        keep.append(i)
        
        x11 = np.maximum(x1[i], x1[index[1:]]) # 左上找尽量右下    # calculate the points of overlap 
        y11 = np.maximum(y1[i], y1[index[1:]])
        x22 = np.minimum(x2[i], x2[index[1:]]) # 右下找尽量左上 
        y22 = np.minimum(y2[i], y2[index[1:]])
        # 以[x11, y11, x22,y22] 构成的矩形是与 最高分数相交的矩形

        w = np.maximum(0, x22-x11+1) # 这里可能是负的(两个矩形不相交),负的这里取宽度为0    # the weights of overlap
        h = np.maximum(0, y22-y11+1)                                                     # the height of overlap
       
        overlaps = w*h
        
        ious = overlaps / (areas[i]+areas[index[1:]] - overlaps)
        
        idx = np.where(ious<=thresh)[0]  # 如果他们的iou小于阈值,说明他们重合的很少,重合的很少的这些框是框的其他目标。
        # 选出重合较少的框(也就是去掉了框中同一个目标,但是分数比较低的框)。
        # 从剩下的里面选择第0位置,也就是剩下的里面选择评分最高的框,进行下次 去iou大的框操作。


        index = index[idx+1]   # because index start from 1
        
    return keep
        

import matplotlib.pyplot as plt
def plot_bbox(dets, c='k'):
    
    x1 = dets[:,0]
    y1 = dets[:,1]
    x2 = dets[:,2]
    y2 = dets[:,3]
    
    
    plt.plot([x1,x2], [y1,y1], c) # plot([起点横坐标,终点横坐标],[起点纵左边, 终点纵坐标])
    plt.plot([x1,x1], [y1,y2], c)
    plt.plot([x1,x2], [y2,y2], c)
    plt.plot([x2,x2], [y1,y2], c)
    plt.title("after nms")
    
plt.subplot(121)
plot_bbox(boxes,'k')   # before nms

plt.subplot(122)
keep = py_cpu_nms(boxes, thresh=0.7)
plot_bbox(boxes[keep], 'r')# after nms
plt.show()

你可能感兴趣的:(NMS的各种实现和速度对比)