【NMS】

【NMS】-非极大值抑制

nms 算法过程

  1. 将所有框的得分排序,选中最高分及其对应的框
  2. 遍历其余的框,如果和当前最高分框的重叠面积(IOU)大于一定阈值,我们将框删除
  3. 从未处理的框中继续选一个得分最高的,重复上述过程
'''
比如:A、B、C、D、E、F、G、H、I、J
假设 A 的得分最高,IOU>0.7,剔除

1. 计算与A的 IOU,  若 BEG(和A的IOU) > 0.7  , 剔除 BEG
2. 若剩下 C、D、F、H、I、J 中F得分最高,计算和F的IOU  DHI > 0.7 剔除
3. 若 C、J 中C得分最高,J与C计算IOU,若结果>0.7  剔除J

输出3个目标 A/F/C
'''
'''
1. 计算候选框的面积时加1?
候选框面积算的是像素点数,比如候选框左上和右下点坐标相同时,面积应该为1,如果计算面积时不+1,候选框面积就变成0了
'''
import numpy as np

def py_nms(dets, thresh):
    '''
    Pure Python NMS baseline
    @ dets = [x1,y1,x2,y2,scores]
    @ thresh 阈值
    '''
    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]     # order是按照score降序排序的

    keep = []   # 最后保留的边框
    while order.size > 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:重叠面积/(面积1+面积2-重叠面积)
        ovr = inter / (areas[i] + areas[order[1:]] - inter)

        #找到重叠度不高于阈值的矩形框索引
        inds = np.where(ovr <= thresh)[0]
        '''将order序列更新,由于前面得到的矩形框索引要比矩形框在原order序列中的索引小1,所以要把这个1加回来'''
        order = order[inds + 1]  
    return keep

# test
if __name__ == "__main__":
    dets = np.array([[30, 20, 230, 200, 1], 
                     [50, 50, 260, 220, 0.9],
                     [210, 30, 420, 5, 0.8],
                     [430, 280, 460, 360, 0.7]])
    thresh = 0.35
    keep_dets = py_nms(dets, thresh)
    
    print(keep_dets)
    print(dets[keep_dets])
[0, 2, 3]
[[  30.    20.   230.   200.     1. ]
 [ 210.    30.   420.     5.     0.8]
 [ 430.   280.   460.   360.     0.7]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值