nms 实现

序言

nms被用在检测的后处理,目的是剔除多余的检测框。接下来用numpy array实现。

注意点

np.maximum和np.minimum是用来返回对应位置的最大值和最小值。np.argsort是用来返回排序后的位置索引。

代码

import numpy as np
import pdb

def cal_iou(box1, box2):
    xx1 = np.maximum(box1[:, 0], box2[:, 0])
    yy1 = np.maximum(box1[:, 1], box2[:, 1]) 
    xx2 = np.minimum(box1[:, 2], box2[:, 2])
    yy2 = np.minimum(box1[:, 3], box2[:, 3])
    union = (xx2-xx1)*(yy2-yy1)
    area1 = (box1[:, 2]-box1[:, 0])*(box1[:, 3]-box1[:, 1])
    area2 = (box2[:, 2]-box2[:, 0])*(box2[:, 3]-box2[:, 1])
    ious = union/area1+area2-union
    return ious


def nms(detections, nms_thre=0.5):
    """
    detections[[xmin, ymin, xmax, ymax, score],
               [xmin, ymin, xmax, ymax, score],
               [xmin, ymin, xmax, ymax, score],
               ...]
    """
    detections = np.array(detections)
    order = np.argsort(detections[:, -1])[::-1]
    detections = detections[order]
    keep = []
    while len(detections):
        keep.append(detections[0])
        best_box = detections[0][np.newaxis,:]
        ious = cal_iou(best_box, detections)
        valid = ious > nms_thre
        detections = detections[~valid]
        
    keep = np.array(keep)
    return keep


if __name__ == "__main__":
    detections = [[100, 50, 150, 100, 0.7],
                  [120, 60, 150, 100, 0.6],
                  [110, 60, 150, 100, 0.5],
                  [80, 30, 180, 120, 0.9],
                  [110, 60, 150, 100, 0.2],]
    result = nms(detections)
    print(result)

结果

[[ 80.   30.  180.  120.    0.9]
 [100.   50.  150.  100.    0.7]
 [120.   60.  150.  100.    0.6]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超超爱AI

土豪请把你的零钱给我点

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值