Python实现非极大值抑制算法(NMS)

import cv2
import numpy as np


def nms(bounding_boxes, confidence_score, threshold):
    '''
    :param bounding_boxes: 候选框列表,[左上角坐标, 右下角坐标], [min_x, min_y, max_x, max_y], 原点在图像左上角
    :param confidence_score: 候选框置信度
    :param threshold: IOU阈值
    :return: 抑制后的bbox和置信度
    '''
    # 如果没有bbox,则返回空列表
    if len(bounding_boxes) == 0:
        return [], []

    # bbox转为numpy格式方便计算
    boxes = np.array(bounding_boxes)

    # 分别取出bbox的坐标
    start_x = boxes[:, 0]
    start_y = boxes[:, 1]
    end_x = boxes[:, 2]
    end_y = boxes[:, 3]

    # 置信度转为numpy格式方便计算
    score = np.array(confidence_score)  # [0.9  0.75 0.8  0.85]

    # 筛选后的bbox和置信度
    picked_boxes = []
    picked_score = []

    # 计算每一个框的面积
    areas = (end_x - start_x + 1) * (end_y - start_y + 1)

    # 将score中的元素从小到大排列,提取其对应的index(索引),然后输出到order
    order = np.argsort(score)   # [1 2 3 0]

    # Iterate bounding boxes
    while order.size > 0:

        # The index of largest confidence score
        # 取出最大置信度的索引
        index = order[-1]

        # Pick the bounding box with largest confidence score
        # 将最大置信度和最大置信度对应的框添加进筛选列表里
        picked_boxes.append(bounding_boxes[index])
        picked_score.append(confidence_score[index])

        # 求置信度最大的框与其他所有框相交的长宽,为下面计算相交面积做准备
        # 令左上角为原点,
        # 两个框的左上角坐标x取大值,右下角坐标x取小值,小值-大值+1==相交区域的长度
        # 两个框的左上角坐标y取大值,右下角坐标y取小值,小值-大值+1==相交区域的高度
        # 这里可以在草稿纸上画个图,清晰明了
        x1 = np.maximum(start_x[index], start_x[order[:-1]])
        x2 = np.minimum(end_x[index], end_x[order[:-1]])
        y1 = np.maximum(start_y[index], start_y[order[:-1]])
        y2 = np.minimum(end_y[index], end_y[order[:-1]])

        # 计算相交面积,当两个框不相交时,w和h必有一个为0,面积也为0
        w = np.maximum(0.0, x2 - x1 + 1)
        h = np.maximum(0.0, y2 - y1 + 1)
        intersection = w * h

        # 计算IOU
        ratio = intersection / (areas[index] + areas[order[:-1]] - intersection)

        # 保留小于阈值的框的索引
        left = np.where(ratio < threshold)
        # 根据该索引修正order中的索引(order里放的是按置信度从小到大排列的索引)
        order = order[left]

    return picked_boxes, picked_score


# 图像路径
image_name = 'lena.jpg'

# 自己设定候选框
bounding_boxes = [(210, 180, 337, 380), (180, 120, 330, 340), (270, 160, 350, 360), (220, 210, 345, 410)]
confidence_score = [0.9, 0.75, 0.8, 0.85]

# 读取图像
image = cv2.imread(image_name)

# 复制一份原图矩阵
org = image.copy()

# 画框参数
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 1
thickness = 2

# IOU阈值设定
threshold = 0.4

# 画框(未运行NMS)
for (start_x, start_y, end_x, end_y), confidence in zip(bounding_boxes, confidence_score):
    (w, h), baseline = cv2.getTextSize(str(confidence), font, font_scale, thickness)
    cv2.rectangle(org, (start_x, start_y - (2 * baseline + 5)), (start_x + w, start_y), (0, 255, 255), -1)
    cv2.rectangle(org, (start_x, start_y), (end_x, end_y), (0, 255, 255), 2)
    cv2.putText(org, str(confidence), (start_x, start_y), font, font_scale, (0, 0, 0), thickness)

# 运行NMS算法
picked_boxes, picked_score = nms(bounding_boxes, confidence_score, threshold)

# 画框(运行了NMS后)
for (start_x, start_y, end_x, end_y), confidence in zip(picked_boxes, picked_score):
    (w, h), baseline = cv2.getTextSize(str(confidence), font, font_scale, thickness)
    cv2.rectangle(image, (start_x, start_y - (2 * baseline + 5)), (start_x + w, start_y), (0, 255, 255), -1)
    cv2.rectangle(image, (start_x, start_y), (end_x, end_y), (0, 255, 255), 2)
    cv2.putText(image, str(confidence), (start_x, start_y), font, font_scale, (0, 0, 0), thickness)

# 展示图像
cv2.imshow('Original', org)
cv2.imshow('NMS', image)
cv2.waitKey(0)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python中的非极大值抑制(Non-Maximum Suppression,简称NMS)是一种常用的目标检测算法,用于在重叠的候选框中选择最佳的目标框。它通常用于物体检测任务中,例如目标检测、人脸检测等。 NMS的基本思想是,在一组候选框中,首先选择具有最高置信度的框作为输出框,然后计算该框与其他候选框的重叠程度(如IoU),如果重叠程度高于一定阈值,则将该候选框剔除。这样可以确保输出的目标框之间没有太大的重叠,从而提高检测结果的准确性。 在Python中,可以使用以下步骤实现非极大值抑制: 1. 根据置信度对候选框进行排序,将置信度最高的框作为输出框。 2. 计算输出框与其他候选框的重叠程度(如IoU)。 3. 对于重叠程度高于设定阈值的候选框,将其从候选框列表中移除。 4. 重复步骤2和步骤3,直到所有候选框都被处理完毕。 5. 返回最终的输出框列表作为非极大值抑制的结果。 以下是一个简单的Python示例代码,演示了如何实现非极大值抑制: ```python def non_maximum_suppression(boxes, scores, threshold): # 根据置信度对候选框进行排序 sorted_indices = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True) selected_indices = [] while sorted_indices: # 选择置信度最高的框作为输出框 best_index = sorted_indices[0] selected_indices.append(best_index) # 计算输出框与其他候选框的重叠程度 best_box = boxes[best_index] other_indices = sorted_indices[1:] overlaps = [calculate_iou(best_box, boxes[i]) for i in other_indices] # 移除重叠程度高于阈值的候选框 filtered_indices = [i for i, overlap in zip(other_indices, overlaps) if overlap <= threshold] sorted_indices = filtered_indices return selected_indices # 计算两个框的重叠程度(IoU) def calculate_iou(box1, box2): # 计算两个框的相交区域 intersection = max(0, min(box1[2], box2[2]) - max(box1[0], box2[0])) * max(0, min(box1[3], box2[3]) - max(box1[1], box2[1])) # 计算两个框的并集区域 area1 = (box1[2] - box1[0]) * (box1[3] - box1[1]) area2 = (box2[2] - box2[0]) * (box2[3] - box2[1]) union = area1 + area2 - intersection # 计算IoU iou = intersection / union return iou # 示例用法 boxes = [[10, 10, 50, 50], [20, 20, 60, 60], [30, 30, 70, 70]] scores = [0.9, 0.8, 0.7] threshold = 0.5 selected_indices = non_maximum_suppression(boxes, scores, threshold) selected_boxes = [boxes[i] for i in selected_indices] print(selected_boxes) ``` 这段代码中,`boxes`表示候选框的坐标,`scores`表示候选框的置信度,`threshold`表示重叠程度的阈值。最后输出的`selected_boxes`即为经过非极大值抑制后的最终输出框。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值