nms实现

手撕IOU

import numpy as np

def cal_iou(box1, box2):
    # box [x1, y1, x2, y2]
    x1 = np.max(box1[0], box2[0])
    y1 = np.max(box1[1], box2[1])
    x2 = np.min(box1[2], box2[2])
    y2 = np.min(box1[3], box2[3])
    inter = np.max((x2 - x1 + 1) * (y2 - y1 + 1), 0) # 若小于0表示不相交

    over = (box1[2] - box1[0] + 1) * (box1[3] - box1[1] + 1) + \
           (box2[2] - box2[0] + 1) * (box2[3] - box2[1] + 1) - \
           inter

    iou = inter / over

    return iou

手撕NMS

1.对所有预测框的置信度降序排序
2.选出置信度最高的预测框,确认其为正确预测,并计算其与剩余预测框的IOU
3.若IOU>threshold阈值表示重叠度过高,将其删除
4.重复上述过程处理完所有检测框

def py_cpu_nms(dets, thresh):
    """Pure Python NMS baseline."""
    #x1、y1、x2、y2、以及score赋值
    x1 = dets[:, 0]
    y1 = dets[:, 1]
    x2 = dets[:, 2]
    y2 = dets[:, 3]
    scores = dets[:, 4]

    #每一个检测框的面积
    areas = (x2 - x1 + 1) * (y2 - y1 + 1)
    #按照score置信度降序排序
    order = scores.argsort()[::-1]

    keep = [] #保留的结果框集合
    while order.size > 0:
        i = order[0]
        keep.append(i) #保留该类剩余box中得分最高的一个
        #得到相交区域,左上及右下
        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:]])

        #计算相交的面积,不重叠时面积为0
        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)
        #保留IoU小于阈值的box
        inds = np.where(ovr <= thresh)[0]
        order = order[inds + 1] #因为ovr数组的长度比order数组少一个,所以这里要将所有下标后移一位
       
    return keep

参考:
https://www.cnblogs.com/makefile/p/nms.html
https://mp.weixin.qq.com/s/8Tjw49w2mZRImtCo2CYncw

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值