Bootstrap

nms实现

手撕IOU

import numpy as np

def cal_iou(box1, box2):
    # box [x1, y1, x2, y2]
    x1 = np.max(box1[0], box2[0])
    y1 = np.max(box1[1], box2[1])
    x2 = np.min(box1[2], box2[2])
    y2 = np.min(box1[3], box2[3])
    inter = np.max((x2 - x1 + 1) * (y2 - y1 + 1), 0) # 若小于0表示不相交

    over = (box1[2] - box1[0] + 1) * (box1[3] - box1[1] + 1) + \
           (box2[2] - box2[0] + 1) * (box2[3] - box2[1] + 1) - \
           inter

    iou = inter / over

    return iou

手撕NMS

1.对所有预测框的置信度降序排序
2.选出置信度最高的预测框,确认其为正确预测,并计算其与剩余预测框的IOU
3.若IOU>threshold阈值表示重叠度过高,将其删除
4.重复上述过程处理完所有检测框

def py_cpu_nms(dets, thresh):
    """Pure Python NMS baseline."""
    #x1、y1、x2、y2、以及score赋值
    x1 = dets[:, 0]
    y1 = dets[:, 1]
    x2 = dets[:, 2]
    y2 = dets[:, 3]
    scores = dets[:, 4]

    #每一个检测框的面积
    areas = (x2 - x1 + 1) * (y2 - y1 + 1)
    #按照score置信度降序排序
    order = scores.argsort()[::-1]

    keep = [] #保留的结果框集合
    while order.size > 0:
        i = order[0]
        keep.append(i) #保留该类剩余box中得分最高的一个
        #得到相交区域,左上及右下
        xx1 = np.maximum(x1[i], x1[order[1:]])
        yy1 = np.maximum(y1[i], y1[order[1:]])
        xx2 = np.minimum(x2[i], x2[order[1:]])
        yy2 = np.minimum(y2[i], y2[order[1:]])

        #计算相交的面积,不重叠时面积为0
        w = np.maximum(0.0, xx2 - xx1 + 1)
        h = np.maximum(0.0, yy2 - yy1 + 1)
        inter = w * h
        #计算IoU:重叠面积 /(面积1+面积2-重叠面积)
        ovr = inter / (areas[i] + areas[order[1:]] - inter)
        #保留IoU小于阈值的box
        inds = np.where(ovr <= thresh)[0]
        order = order[inds + 1] #因为ovr数组的长度比order数组少一个,所以这里要将所有下标后移一位
       
    return keep

参考:
https://www.cnblogs.com/makefile/p/nms.html
https://mp.weixin.qq.com/s/8Tjw49w2mZRImtCo2CYncw

;