Non-maximum suppression python实现

# coding=utf-8

import numpy as np
import cv2


def nms(bboxs, thresh):

    # get all parameters
    x1, y1, x2, y2, scores = [bboxs[:, i] for i in range(len(bboxs[0]))]

    # calculate all areas of boxed
    areas = (x2 - x1 + 1) * (y2 - y1 + 1)

    # sort boxes according to their class score
    sorted_index = scores.argsort()[::-1]

    # result list
    result = []

    while sorted_index.size > 0:
        # get the box with largest score
        max_box = bboxs[sorted_index[0]]

        # add it to our result
        result.append(max_box)

        # calculate intersection coordinates
        xx1 = np.maximum(max_box[0], x1[sorted_index[1:]])
        yy1 = np.maximum(max_box[1], y1[sorted_index[1:]])
        xx2 = np.minimum(max_box[2], x2[sorted_index[1:]])
        yy2 = np.minimum(max_box[3], y2[sorted_index[1:]])

        # calculate intersection area
        w = np.maximum(0.0, xx2 - xx1 + 1)
        h = np.maximum(0.0, yy2 - yy1 + 1)
        intersection = w * h

        # calculate ious
        ious = intersection / (areas[sorted_index[0]] + areas[sorted_index[1:]] - intersection)

        # retain all the boxes whose ious are less than the threshold
        sorted_index = sorted_index[1:][ious <= thresh]

    return result


def draw_bbox(bboxs, pic_name):
    pic = np.zeros((850, 850), np.uint8)
    for bbox in bboxs:
        x1, y1, x2, y2 = map(int, bbox[:-1])
        pic = cv2.rectangle(pic, (x1, y1), (x2, y2), (255, 0, 0), 2)
    cv2.imshow(pic_name,pic)
    cv2.waitKey(0)


if __name__ == "__main__":
    bboxs = np.array([
        [720, 690, 820, 800, 0.5],
        [204, 102, 358, 250, 0.5],
        [257, 118, 380, 250, 0.8],
        [700, 700, 800, 800, 0.4],
        [280, 135, 400, 250, 0.7],
        [255, 118, 360, 235, 0.7]])
    thresh = 0.3
    draw_bbox(bboxs, "Before_NMS")
    result = nms(bboxs, thresh)
    draw_bbox(result, "After_NMS")

modified from:

https://blog.csdn.net/JNingWei/article/details/78977812?utm_source=blogxgwz3

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值