NMS和soft-NMS原理和代码实现

NMS

python实现代码:

import numpy as np
import matplotlib.pyplot as plt


def py_cpu_nms(dets, thresh):

   x1 = dets[:, 0]
   y1 = dets[:, 1]
   x2 = dets[:, 2]
   y2 = dets[:, 3]
   scores = dets[:, 4]
   areas = (x2-x1+1)*(y2-y1+1)
   res = []
   index = scores.argsort()[::-1]
   while index.size>0:
       i = index[0]
       res.append(i)
       x11 = np.maximum(x1[i],x1[index[1:]])
       y11 = np.maximum(y1[i], y1[index[1:]])
       x22 = np.minimum(x2[i],x2[index[1:]])
       y22 = np.minimum(y2[i],y2[index[1:]])

       w = np.maximum(0,x22-x11+1)
       h = np.maximum(0,y22-y11+1)

       overlaps = w * h
       iou = overlaps/(areas[i]+areas[index[1:]]-overlaps)

       idx = np.where(iou<=thresh)[0]
       index = index[idx+1]
   print(res)
   return res

def plot_boxs(box,c):
    x1 = box[:, 0]
    y1 = box[:, 1]
    x2 = box[:, 2]
    y2 = box[:, 3]

    plt.plot([x1,x2],[y1,y1],c)
    plt.plot([x1,x2],[y2,y2],c)
    plt.plot([x1,x1],[y1,y2],c)
    plt.plot([x2,x2],[y1,y2],c)
    
if __name__ == '__main__':
    boxes = np.array([[100, 100, 210, 210, 0.72],
                      [250, 250, 420, 420, 0.8],
                      [220, 220, 320, 330, 0.92],
                      [230, 240, 325, 330, 0.81],
                      [220, 230, 315, 340, 0.9]])
    plt.figure()
    ax1 = plt.subplot(121)
    ax2 = plt.subplot(122)
    plt.sca(ax1)
    plot_boxs(boxes,'k')

    res = py_cpu_nms(boxes,0.7)
    plt.sca(ax2)
    plot_boxs(boxes[res],'r')
    plt.show()

在这里插入图片描述

soft-NMS

论文(CVPR2017): 《Improving Object Detection With One Line of Code》

Soft-NMS的优势

  • 它仅需要对传统的NMS算法进行简单的改动且不增额外的参数。该Soft-NMS算法在标准数据集PASCAL - VOC2007(较R-FCN和Faster-RCNN提升1.7%)和MS-COCO(较R-FCN提升1.3%,较Faster-RCNN提升1.1%)上均有提升。
  • Soft-NMS具有与传统NMS相同的算法复杂度,使用高效。
  • Soft-NMS不需要额外的训练,并易于实现,它可以轻松的被集成到任何物体检测流程中。

原理

见下图伪代码,整个改进只需要使用绿色虚线表示的Soft-NMS替换红色虚线表示的NMS。

B集合是检测到的所有建议框,S集合是各个建议框得分(分数是指建议框包含物体的可能性大小),Nt是指手动设置的阈值。M为当前得分最高框,bi 为待处理框。

在这里插入图片描述

  • f(iou(M,bi))权重函数的形式
    • 原来的NMS可以描述如下:将IoU大于阈值的窗口的得分全部置为0。在这里插入图片描述

    • Soft-NMS的改进有两种形式,一种是线性加权的:
      在这里插入图片描述

    • 一种是高斯加权的:
      在这里插入图片描述

综上,soft-nms的核心就是降低置信度。比如一张人脸上有3个重叠的bounding box, 置信度分别为0.9, 0.7, 0.85 。选择得分最高的建议框,经过第一次处理过后,得分依次变成了0.9, 0.65, 0.55(此时将得分最高的保存在D中)。这时候再选择第二个bounding box作为得分最高的,处理后置信度分别为0.65, 0.45(这时候3个框也都还在),最后选择第三个,处理后得分不改变。最终经过soft-nms抑制后的三个框的置信度分别为0.9, 0.65, 0.45。最后设置阈值,将得分si小于阈值的去掉。

效果示例

在这里插入图片描述
假如还检测出了3号框,而我们的最终目标是检测出1号和2号框,并且剔除3号框,原始的nms只会检测出一个1号框并剔除2号框和3号框,而softnms算法可以对1、2、3号检测狂进行置信度排序,可以知道这三个框的置信度从大到小的顺序依次为:1-》2-》3(由于是使用了惩罚,IoU越大,得分越低,所有可以获得这种大小关系),如果我们再选择了合适的置信度阈值,就可以保留1号和2号,同时剔除3号,实现我们的功能。

但是,这里也有一个问题就是置信度的阈值如何选择,作者在这里依然使用手工设置的值,依然存在很大的局限性,所以该算法依然存在改进的空间。

参考:https://zhuanlan.zhihu.com/p/41046620

nms和soft-nms代码对比


import matplotlib.pyplot as plt
import numpy as np

boxes = np.array([[100, 100, 210, 210, 0.1],
                  [250, 250, 420, 420, 0.8],
                  [220, 220, 320, 330, 0.92],
                  [100, 100, 240, 240, 0.72],
                  [230, 240, 325, 330, 0.81],
                  [220, 230, 315, 340, 0.9]])  # (x1,y1,x2,y2,score)


def nms(boxes, threshold):
    x1 = boxes[:, 0]
    y1 = boxes[:, 1]
    x2 = boxes[:, 2]
    y2 = boxes[:, 3]
    scores = boxes[:, 4]
    areas = (x2 - x1 + 1) * (y2 - y1 + 1)

    keep = []
    idxs = scores.argsort()[::-1]  # 从大到下排序,argsort函数返回从小到大的索引,[::-1]反序变成从大到小
    while (idxs.size > 0):
        i = idxs[0]
        keep.append(i)
        x11 = np.maximum(x1[i], x1[idxs[1:]])
        y11 = np.maximum(y1[i], y1[idxs[1:]])
        x22 = np.minimum(x2[i], y2[idxs[1:]])
        y22 = np.minimum(y2[i], y2[idxs[1:]])

        w = np.maximum(0, x22 - x11 + 1)
        h = np.maximum(0, y22 - y11 + 1)

        overlaps = w * h
        ious = overlaps / (areas[i] + areas[idxs[1:]] - overlaps)
        idxs2 = np.where(ious < threshold)[0]  # np.where函数
        idxs = idxs[idxs2 + 1]  # 注意这个+1

    return keep

#
def soft_nms(boxes, sigma=0.5, threshold1=0.7, threshold2=0.1, method=1):
    '''
    paper:Improving Object Detection With One Line of Code
    '''
    N = boxes.shape[0]
    pos = 0
    maxscore = 0
    maxpos = 0

    for i in range(N):
        maxscore = boxes[i, 4]
        maxpos = i

        tx1 = boxes[i, 0]
        ty1 = boxes[i, 1]
        tx2 = boxes[i, 2]
        ty2 = boxes[i, 3]
        ts = boxes[i, 4]

        pos = i + 1
        # 得到评分最高的box
        while pos < N:
            if maxscore < boxes[pos, 4]:
                maxscore = boxes[pos, 4]
                maxpos = pos
            pos = pos + 1

        # 交换第i个box和评分最高的box,将评分最高的box放到第i个位置
        boxes[i, 0] = boxes[maxpos, 0]
        boxes[i, 1] = boxes[maxpos, 1]
        boxes[i, 2] = boxes[maxpos, 2]
        boxes[i, 3] = boxes[maxpos, 3]
        boxes[i, 4] = boxes[maxpos, 4]

        boxes[maxpos, 0] = tx1
        boxes[maxpos, 1] = ty1
        boxes[maxpos, 2] = tx2
        boxes[maxpos, 3] = ty2
        boxes[maxpos, 4] = ts

        tx1 = boxes[i, 0]
        ty1 = boxes[i, 1]
        tx2 = boxes[i, 2]
        ty2 = boxes[i, 3]
        ts = boxes[i, 4]

        pos = i + 1
        # softNMS迭代
        while pos < N:
            x1 = boxes[pos, 0]
            y1 = boxes[pos, 1]
            x2 = boxes[pos, 2]
            y2 = boxes[pos, 3]
            s = boxes[pos, 4]

            area = (x2 - x1 + 1) * (y2 - y1 + 1)
            iw = (min(tx2, x2) - max(tx1, x1) + 1)
            if iw > 0:
                ih = (min(ty2, y2) - max(ty1, y1) + 1)
                if ih > 0:
                    uinon = float((tx2 - tx1 + 1) *
                                  (ty2 - ty1 + 1) + area - iw * ih)
                    iou = iw * ih / uinon  # 计算iou
                    if method == 1:  # 线性更新分数
                        if iou > threshold1:
                            weight = 1 - iou
                        else:
                            weight = 1
                    elif method == 2:  # 高斯权重
                        weight = np.exp(-(iou * iou) / sigma)
                    else:  # 传统 NMS
                        if iou > threshold1:
                            weight = 0
                        else:
                            weight = 1

                    boxes[pos, 4] = weight * boxes[pos, 4]  # 根据和最高分数box的iou来更新分数

                    # 如果box分数太低,舍弃(把他放到最后,同时N-1)
                    if boxes[pos, 4] < threshold2:
                        boxes[pos, 0] = boxes[N - 1, 0]
                        boxes[pos, 1] = boxes[N - 1, 1]
                        boxes[pos, 2] = boxes[N - 1, 2]
                        boxes[pos, 3] = boxes[N - 1, 3]
                        boxes[pos, 4] = boxes[N - 1, 4]
                        N = N - 1  # 注意这里N改变
                        pos = pos - 1

            pos = pos + 1

    keep = [i for i in range(N)]
    return keep
def plot_boxs(box,c):
    x1 = box[:, 0]
    y1 = box[:, 1]
    x2 = box[:, 2]
    y2 = box[:, 3]

    plt.plot([x1,x2],[y1,y1],c)
    plt.plot([x1,x2],[y2,y2],c)
    plt.plot([x1,x1],[y1,y2],c)
    plt.plot([x2,x2],[y1,y2],c)

keep1 = nms(boxes, 0.7)
keep2 = soft_nms(boxes)
print(keep1,'|||',keep2)
print("end")
plt.figure()
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)
plt.sca(ax1)
plot_boxs(boxes,'k')

plt.sca(ax2)
plot_boxs(boxes[keep1],'k')

plt.sca(ax3)
plot_boxs(boxes[keep2],'r')
plt.show()

结果
在这里插入图片描述

  • 7
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: soft-nms pytorch源代码是一个基于PyTorch框架实现的软非极大值抑制算法的源代码。该算法可以在目标检测中用于抑制重叠的检测框,从而提高检测的准确性和效率。该源代码提供了一个简单易用的接口,可以方便地集成到现有的目标检测系统中。 ### 回答2: Soft-NMS是一种针对目标检测中非极大值抑制(Non-Maximum Suppression, NMS)的改进算法。Soft-NMS的目的是尽可能保留更多的检测结果,其中,保留哪些检测结果以及去除哪些检测结果是通过计算每个检测框和其他检测框的IoU(Intersection over Union)来决定的。 PyTorch是一个流行的深度学习框架,在PyTorch中实现Soft-NMS非常简单。下面是PyTorch官方提供的Soft-NMS代码: ```python def soft_nms(dets, sigma=0.5, Nt=0.3, threshold=0.001, method=2): """ :param dets: [[x1, y1, x2, y2, score], ...] :param sigma: :param Nt: :param threshold: :param method: :return: indexes to keep """ N = dets.shape[0] indexes = np.arange(N) for i in range(N): pos = i + 1 if i != N - 1: maximum = np.argmax(dets[pos:, 4]) if dets[i, 4] < dets[maximum + pos, 4]: dets[[i, maximum + pos], :] = dets[[maximum + pos, i], :] indexes[[i, maximum + pos]] = indexes[[maximum + pos, i]] t_bbox, t_score = dets[i, :4], dets[i, 4] if method == 1: weight = np.exp(-(np.power((dets[i + 1:, :4] - t_bbox), 2).sum(1) / sigma)) else: weight = np.zeros((N - i - 1,)) _idx = np.where(dets[i + 1:, 4] >= Nt)[0] + i + 1 if len(_idx) > 0: ex_dets = dets[_idx, :] overlap = iou(t_bbox.reshape(1, -1), ex_dets[:, :4]) weight[_idx - (i + 1)] = overlap weight = np.exp(-(weight * weight) / sigma) dets[i + 1:, 4] *= weight score_mask = dets[i + 1:, 4] >= threshold indexes_mask = indexes[i + 1:][score_mask] dets[i + 1:, :] = dets[indexes_mask, :] indexes[i + 1:] = indexes[indexes_mask] if len(indexes_mask) == 0: break keep = np.zeros(N, dtype=np.intp) keep[indexes] = 1 return np.where(keep == 1)[0] ``` 这里,soft_nms函数接受一个包含检测结果的二维数组dets,其中每个元素包含四个坐标[x1, y1, x2, y2]和一个分数score。函数的其他参数包括sigma、Nt、threshold和method等。 对于每个检测框,软NMS算法首先检查其余检测框的IoU。如果另一个检测框的IoU高于给定的Nt阈值,则它的分数将被调整到小于原始分数因子*(1-IoU)。然后,score_mask掩码被用来删掉具有较低分数的检测框,直到达到需要的最终物体数或所有框都不再死亡。最后,保留下来的检测框的索引被返回给用户。 这个PyTorch源代码是一个很好的例子,可以帮助我们了解如何使用Python来自定义各种优化算法,包括Soft-NMS。 ### 回答3: Soft-NMS是一种基于非极大抑制(NMS)的目标检测算法。与传统的NMS算法不同,Soft-NMS通过对重叠框之间的分数进行加权来降低框的置信度,而不是直接将框丢弃。这样可以在一定程度上保留重叠框中的信息。 PyTorch是一种流行的深度学习框架,提供了供用户使用的许多预定义算法和函数。PyTorch实现Soft-NMS的源代码,这使得用户可以直接使用这种功能而不必手动实现。 在PyTorch中,Soft-NMS实现是在torchvision.ops.nms.soft_nms中完成的。它有以下四个参数: - boxes: 包含所有检测框的tensor。 - scores: 所有检测框的分数。 - iou_threshold: 重叠IOU阈值。如果两个框之间的IOU低于此阈值,则不会执行Soft-NMS。 - score_threshold: 分数阈值。如果框的分数低于此阈值,则不会执行Soft-NMS。 整个NMS算法的流程如下: 1. 将分数从高到低排序,并将相应的边界框记录下来。 2. 选择分数最高的框,并记录下该框的索引号。 3. 计算该框与所有其他框之间的IOU值,并使用Soft-NMS算法对其进行加权。 4. 删除其余重叠框,并在剩下的框中重复步骤2-4,直到所有框都被处理。 调用soft_nms函数后,将返回保留下来框的索引列表。然后可以使用这个索引列表来关联boxes和scores,并对检测到的目标进行可视化或其他后处理操作。 在使用Soft-NMS时,需要根据具体情况调整两个阈值。如果两个阈值设置得太低,可能会误保留一些低质量的检测框。如果设置得过高,可能会丢失一些真实的目标。因此,建议在数据集上进行测量和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shashank497

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值