numpy实现NMS

该博客介绍了非极大值抑制(NMS)算法的Python实现,用于处理目标检测中框的筛选。代码首先定义了py_cpu_nms函数,通过计算重叠区域和IoU来消除高重叠度的检测框。然后通过示例展示了如何在Matplotlib中绘制检测框,并使用NMS算法进行过滤。最后,给出了一个包含多个检测框的实例,演示了NMS算法的效果。
摘要由CSDN通过智能技术生成
import numpy as np
import matplotlib.pyplot as plt


def py_cpu_nms(dets, thresh):

   x1 = dets[:, 0]
   y1 = dets[:, 1]
   x2 = dets[:, 2]
   y2 = dets[:, 3]
   scores = dets[:, 4]
   areas = (x2-x1+1)*(y2-y1+1)
   res = []
   index = scores.argsort()[::-1]
   while index.size>0:
       i = index[0]
       res.append(i)
       x11 = np.maximum(x1[i],x1[index[1:]])
       y11 = np.maximum(y1[i], y1[index[1:]])
       x22 = np.minimum(x2[i],x2[index[1:]])
       y22 = np.minimum(y2[i],y2[index[1:]])

       w = np.maximum(0,x22-x11+1)
       h = np.maximum(0,y22-y11+1)

       overlaps = w * h
       iou = overlaps/(areas[i]+areas[index[1:]]-overlaps)

       idx = np.where(iou<=thresh)[0]
       index = index[idx+1]
   print(res)
   return res

def plot_boxs(box,c):
    x1 = box[:, 0]
    y1 = box[:, 1]
    x2 = box[:, 2]
    y2 = box[:, 3]

    plt.plot([x1,x2],[y1,y1],c)
    plt.plot([x1,x2],[y2,y2],c)
    plt.plot([x1,x1],[y1,y2],c)
    plt.plot([x2,x2],[y1,y2],c)
    
if __name__ == '__main__':
    boxes = np.array([[100, 100, 210, 210, 0.72],
                      [250, 250, 420, 420, 0.8],
                      [220, 220, 320, 330, 0.92],
                      [230, 240, 325, 330, 0.81],
                      [220, 230, 315, 340, 0.9]])
    plt.figure()
    ax1 = plt.subplot(121)
    ax2 = plt.subplot(122)
    plt.sca(ax1)
    plot_boxs(boxes,'k')

    res = py_cpu_nms(boxes,0.7)
    plt.sca(ax2)
    plot_boxs(boxes[res],'r')
    plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Shashank497

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值