nms python代码_NMS python实现

该博客介绍了如何使用Python实现非极大值抑制(NMS)算法,通过cv2和numpy库处理边界框,计算相交区域并进行重叠判断,以消除检测目标的重复。
摘要由CSDN通过智能技术生成

import cv2

import numpy as np

def nms(bounding_boxes, confidence_score, threshold):

if len(bounding_boxes) == 0:

return [], []

boxes = np.array(bounding_boxes)

score = np.array(confidence_score)

# 取出所有候选区域的左上角和右下角的点坐标

start_x = boxes[:, 0]

start_y = boxes[:, 1]

end_x = boxes[:, 2]

end_y = boxes[:, 3]

picked_boxes = []

picked_scores = []

# 计算每个候选区域的面积

areas = (end_x - start_x + 1) * (end_y - start_y + 1)

# np.argsort(x)为从小到大排序 np.argsort(-x)为从大到小排序

order = np.argsort(score)

# 当order不为空

while order.size > 0:

# 选取最大置信度(score)的index

index = order[-1]

picked_boxes.append(bounding_boxes[index])

picked_score.append(confidence_score[index])

# 计算相交区域左上角和右下角两点坐标

x1 = np.maximum(start_x[index], start_x[order[:-1]])

y1 = np.maximum(start_y[index], start_y[order[:-1]])

x2 = np.minimum(end_x[index], end_x[order[:-1]])

y2 = np.minimum(end_y[index], end_y[order[:-1]])

# 计算相交区域面积

w = np.maximum(0.0, x2 - x1 + 1)

h = np.maximum(0.0, y2 - y1 + 1)

intersection = w * h

# 计算交并比

ratio = intersection / (area[index] + area[order[:-1]] - intersection)

# 保留所有重叠面积小于阈值的框,留作下次处理

left = np.where(ratio < threshold)

order = order[left]

return picked_boxes, picked_score

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值