学生面试题:请使用Python写出NMS的实现过程,有意思还有问这个的???

# coding=utf-8
# @Author : JiMi_Wang

"""
请使用Python写出NMS的实现过程,并输入数据测试
bounding = [(187, 82, 337, 317), (150, 67, 305, 282), (246, 121, 368, 304)],
confidence_score = [0.9, 0.75, 0.8]。threshold = 0.4。得到正确结果
"""
import numpy as np
def nms(bboxes, confidence_score, threshold):
    """非极大抑制过程
    :param bboxes: 同类别候选框坐标
    :param confidence: 同类别候选框分数
    :param threshold: iou阈值
    :return: picked_boxes, picked_score分类结果框
    """
    # 1、传入无候选框返回空
    if len(bboxes) == 0:
        return [], []
    # 强转数组
    bboxes = np.array(bboxes)
    score = np.array(confidence_score)
    # print(score)
    # [0.9  0.75 0.8 ]

    # print(bboxes)
    # [[187  82 337 317]
    #  [150  67 305 282]
    #  [246 121 368 304]]
    # 取出n个的极坐标点
    x1 = bboxes[:, 0]
    y1 = bboxes[:, 1]
    x2 = bboxes[:, 2]
    y2 = bboxes[:, 3]
    # print(x1)
    # print(x2)
    # [187 150 246]
    # [337 305 368]
    # print("--------------------------")
    # print(x2-x1)
    # print(y2-y1)
    # [150 155 122]
    # [235 215 183]

    # 矩形框面积的集合(矩阵操作)
    areas = (x2 - x1) * (y2 - y1)
    # print(areas)
    # [35250 33325 22326]

    # 2、对候选框进行NMS筛选
    # 返回的框坐标和分数
    picked_boxes = []
    picked_score = []
    # 对置信度进行排序, 获取排序后的下标序号, argsort默认从小到大排序
    order = np.argsort(score)
    # index = np.argmax(score)
    # print(index)
    # 0
    print("order:", order)  # order: [1 2 0]
    while order.size > 0:
        # 将当前置信度最大的框加入返回值列表中
        index = order[-1]
        # 保留该类剩余box中得分最高的一个
        picked_boxes.append(bboxes[index])
        picked_score.append(confidence_score[index])

        # 获取当前置信度最大的候选框与其他任意候选框的相交面积
        x11 = np.maximum(x1[index], x1[order[:-1]])
        y11 = np.maximum(y1[index], y1[order[:-1]])
        x22 = np.minimum(x2[index], x2[order[:-1]])
        y22 = np.minimum(y2[index], y2[order[:-1]])
        # 计算相交的面积,不重叠时面积为0
        w = np.maximum(0.0, x22 - x11)
        h = np.maximum(0.0, y22 - y11)
        intersection = w * h

        # 利用相交的面积和两个框自身的面积计算框的交并比
        ratio = intersection / (areas[index] + areas[order[:-1]] - intersection)
        # 保留IoU小于阈值的box
        keep_boxes_indics = np.where(ratio < threshold)
        # 保留剩余的框
        order = order[keep_boxes_indics]
        # 返回NMS后的框及分类结果
    return picked_boxes, picked_score


if __name__ == '__main__':
    bounding = [(187, 82, 337, 317), (150, 67, 305, 282), (246, 121, 368, 304)]
    confidence_score = [0.9, 0.75, 0.8]
    threshold = 0.4
    ret = nms(bounding, confidence_score, threshold)
    print("nms结果:", ret)
    # nms结果: ([array([187,  82, 337, 317])], [0.9])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值