soft_nms实现

nms实现

# 定义一个nms函数
def nms(dets, thresh):
    '''
    input:
        dets: dets是(n,5)的ndarray,第0维度的每个元素代表一个框:[x1, y1, x2, y2, score] 
        thresh: float
    output:
        index
    '''

    x1 = dets[:, 0] # dets:(n,5)  x1:(n,)  dets是ndarray, x1是ndarray
    y1 = dets[:, 1]
    x2 = dets[:, 2]
    y2 = dets[:, 3]
    scores = dets[:, 4] # scores是ndarray


    # 每一个候选框的面积
    areas = (x2 - x1 + 1) * (y2 - y1 + 1) # areas:(n,)

    # order是按照score降序排序的
    order = scores.argsort()[::-1] # order:(n,) 降序下标 order是ndarray


    keep = []
    while order.size > 0:
        i = order[0] # i 是当下分数最高的框的下标
        # print(i)
        keep.append(i)
        # 计算当前概率最大矩形框与其他矩形框的相交框的坐标,会用到numpy的broadcast机制,得到的是向量

        # 当order只有一个值的时候,order[1]会报错说index out of range,而order[1:]会是[],不报错,[]也可以作为x1的索引,x1[[]]为[]
   
        xx1 = np.maximum(x1[i], x1[order[1:]]) # xx1:(n-1,)的ndarray x1[i]:numpy_64浮点数一个,x1[order[1:]]是个ndarray,可以是空的ndarray,如果是空ndarray那么xx1为空ndarray,如果非空,那么x1[order[1:]]有多少个元素,xx1就是有多少个元素的ndarray。x1[]是不是ndarray看中括号内的是不是ndarray,看中括号内的是不是ndarray看中括号内的order[]的中括号内有没有冒号,有冒号的是ndarray,没有的是一个数。
        yy1 = np.maximum(y1[i], y1[order[1:]])
        xx2 = np.minimum(x2[i], x2[order[1:]])
        yy2 = np.minimum(y2[i], y2[order[1:]])
        

        # 计算相交框的面积,注意矩形框不相交时w或h算出来会是负数,用0代替
        w = np.maximum(0.0, xx2 - xx1 + 1) # xx2-xx1是(n-1,)的ndarray,w是(n-1,)的ndarray, n会逐渐减小至1
        # 当xx2和xx1是空的,那w是空的
        h = np.maximum(0.0, yy2 - yy1 + 1)

        inter = w * h # inter是(n,)的ndarray
        # 当w和h是空的,inter是空的

        # 计算重叠度IOU:重叠面积/(面积1+面积2-重叠面积)
        eps = np.finfo(areas.dtype).eps # 除法考虑分母为0的情况,np.finfo(dtype).eps,np.finfo(dtype)是个类,它封装了机器极限浮点类型的数,比如eps,episilon的缩写,表示小正数。
        ovr = inter / np.maximum(eps, areas[i] + areas[order[1:]] - inter) # n-1   #一旦(面积1+面积2-重叠面积)为0,就用eps进行替换
        # 当inter为空,areas[i]无论inter空不空都是有值的,那么ovr也为空


        # 找到重叠度不高于阈值的矩形框索引
        inds = np.where(ovr <= thresh)[0]
        # 当ovr为空, inds为空

        # 将order序列更新,由于前面得到的矩形框索引要比矩形框在原order序列中的索引小1,所以要把这个1加回来
 

        order = order[inds + 1]
        # 当inds为空,原来的order不为空,那么索引后的order为空
        print("order:{}".format(order))


    return keep


import numpy as np
import cv2

# 读入图片,录入原始框([x1, y1, x2, y2, score])
image = cv2.imread('w.jpg')
boxes = np.array([[5,	52,	171,	270, 0.9999],
[13,	1,	179,	268, 0.9998],
[20,	7,	176,	262, 0.8998],
[7,	5,	169,	272, 0.9687],
[3,	43,	162,	256, 0.9786],
[10,	56,	167,	266, 0.8988]])






# 将框绘制在图像上
image_for_nms_box = image.copy()
for box in boxes:
    x1, y1, x2, y2, score = int(box[0]), int(box[1]), int(box[2]), int(box[3]), box[4] # x:col y:row
    image_for_nms_box = cv2.rectangle(image_for_nms_box, (x1, y1), (x2, y2), (0,255,0), 2)
cv2.imwrite("w_all_boxes.jpg", image_for_nms_box)
cv2.imshow('w_all_boxes', image_for_nms_box)

# 使用nms对框进行筛选
keep = nms(boxes, thresh=0.2) # 0.2可以,0.9有很多框存留,因为iou小于thresh才能存留,当设定的thresh过大,存留下来的框就多
nms_boxs = boxes[keep]

# 将筛选过后的框绘制在图像上
image_for_nms_box = image.copy()
for box in nms_boxs:
    x1, y1, x2, y2, score = int(box[0]), int(box[1]), int(box[2]), int(box[3]), box[4] # x:col y:row
    image_for_nms_box = cv2.rectangle(image_for_nms_box, (x1, y1), (x2, y2), (0,255,0), 2)
cv2.imwrite("w_nms.jpg", image_for_nms_box)
cv2.imshow('w_nms', image_for_nms_box)

cv2.waitKey()
cv2.destroyAllWindows()

nms前后效果图

before:
before
after:
在这里插入图片描述

nms存在的问题

如果两个物体 的iou很大,那么网络生成的关于这两个物体的bboxes的iou也很大。nms的做法是,假设第一个物体的某个bbox分数最高,那么这个物体被记录下来,计算它跟其他bbox的iou,如果iou大于某个阈值就把对应的bbox剔除,而跟这个物体的iou很大的物体的bbox就会被剔除掉,也就是上图出现的明明有两个物体,经过nms后只剩下一个bbox的原因。

soft_nms原理

nms的原理可以表示为以下公式:
s i = s i   i f   i o u < t h r e s h , e l s e   0 s_i=s_i\ if\ iou<thresh, else\ 0 si=si if iou<thresh,else 0
s i s_i si代表第i个bbox的分数。
分数粗暴地由iou和thresh决定,当iou很大时直接置为0。
有人提出了soft_max,用于解决nms中两个物体iou很大导致的漏检问题,原理可以表示为以下公式:
s i = s i ∗ e − i o u 2 / σ s_i = s_i * e^{-iou^2/\sigma} si=sieiou2/σ
这样分数由分数本身和iou共同决定,当iou很大时,分数并不会直接置为0,因为 e − x e^{-x} ex是单调递减,极限为0的函数,当x趋于正无穷大的时候才趋于0,本身不会等于0。另外,这个公式还有 s i s_i si作为系数。
同时,它也保留了nms的优点,当两个物体的iou为0是,相互没有影响,因为 e 0 e^0 e0为1, s i = s i s_i=s_i si=si。另外,当两个物体越靠近,iou越大,惩罚越大, s i s_i si越小,这是由于 e − x e^{-x} ex单调递减的性质决定的。
得到了重新赋值的分数,人为设定一个阈值,当分数低于这个阈值,对应的bbox就被剔除,这就是soft_nms。
举个例子,比如上图,物体1 和物体2周围都有很多围绕着各自的框,假设物体1的某个框分数最高,那么这个框被记录。物体1周围的其他框跟这个被记录的框iou比物体2周围的框跟这个被记录的框iou大,所以惩罚更大, s i s_i si越小,并且由于小于阈值,所以被剔除掉了,(这一步可以在代码里打印出来,每次迭代的最后打印被保留下来的框的下标),那么接下来的迭代,一定是物体2周围本身分数最高的框被记录,然后物体2周围的其他框由于跟这个新的被记录的框的iou很大,被剔除掉了,所以最后剩下两个框。

soft_nms的优点

1,解决了物体挨得很近导致的漏检问题
2,需要增加的超参数很少,只增加了一个sigma,阈值nms本来也有,iou是算出来的
3,计算复杂度相对于nms没有增加,都是O(n^2),n是bboxes的数量。

soft_nms实现


import numpy as np

# 定义一个nms函数
def soft_nms(dets, thresh=0.3, sigma=0.5): # score大于thresh的才能存留下来,当设定的thresh过低,存留下来的框就很多,所以要根据实际情况调参
    '''
    input:
        dets: dets是(n,5)的ndarray,第0维度的每个元素代码一个框:[x1, y1, x2, y2, score] 
        thresh: float
        sigma: flaot
    output:
        index
    '''

    x1 = dets[:, 0] # dets:(n,5)  x1:(n,)  dets是ndarray, x1是ndarray
    y1 = dets[:, 1]
    x2 = dets[:, 2]
    y2 = dets[:, 3]
    scores = dets[:, 4] # scores是ndarray


    # 每一个候选框的面积
    areas = (x2 - x1 + 1) * (y2 - y1 + 1) # areas:(n,)

    # order是按照score降序排序的
    order = scores.argsort()[::-1] # order:(n,) 降序下标 order是ndarray


    keep = []
    while order.size > 0:
        i = order[0] # i 是当下分数最高的框的下标
        # print(i)
        keep.append(i)
        # 计算当前概率最大矩形框与其他矩形框的相交框的坐标,会用到numpy的broadcast机制,得到的是向量

        # 当order只有一个值的时候,order[1]会报错说index out of range,而order[1:]会是[],不报错,[]也可以作为x1的索引,x1[[]]为[]
   
        xx1 = np.maximum(x1[i], x1[order[1:]]) # xx1:(n-1,)的ndarray x1[i]:numpy_64浮点数一个,x1[order[1:]]是个ndarray,可以是空的ndarray,如果是空ndarray那么xx1为空ndarray,如果非空,那么x1[order[1:]]有多少个元素,xx1就是有多少个元素的ndarray。x1[]是不是ndarray看中括号内的是不是ndarray,看中括号内的是不是ndarray看中括号内的order[]的中括号内有没有冒号,有冒号的是ndarray,没有的是一个数。
        yy1 = np.maximum(y1[i], y1[order[1:]])
        xx2 = np.minimum(x2[i], x2[order[1:]])
        yy2 = np.minimum(y2[i], y2[order[1:]])
        

        # 计算相交框的面积,注意矩形框不相交时w或h算出来会是负数,用0代替
        w = np.maximum(0.0, xx2 - xx1 + 1) # xx2-xx1是(n-1,)的ndarray,w是(n-1,)的ndarray, n会逐渐减小至1
        # 当xx2和xx1是空的,那w是空的
        h = np.maximum(0.0, yy2 - yy1 + 1)

        inter = w * h # inter是(n,)的ndarray
        # 当w和h是空的,inter是空的

        # 计算重叠度IOU:重叠面积/(面积1+面积2-重叠面积)
        eps = np.finfo(areas.dtype).eps # 除法考虑分母为0的情况,np.finfo(dtype).eps,np.finfo(dtype)是个类,它封装了机器极限浮点类型的数,比如eps,episilon的缩写,表示小正数。
        ovr = inter / np.maximum(eps, areas[i] + areas[order[1:]] - inter) # n-1   #一旦(面积1+面积2-重叠面积)为0,就用eps进行替换
        # 当inter为空,areas[i]无论inter空不空都是有值的,那么ovr也为空

        # 更新分数
        weight = np.exp(-ovr*ovr/sigma)
        scores[order[1:]] *= weight

        # 更新order
        score_order = scores[order[1:]].argsort()[::-1] + 1
        order = order[score_order]

        keep_ids = np.where(scores[order]>thresh)[0]

        order = order[keep_ids]


    return keep


import numpy as np
import cv2

# 读入图片,录入原始人框([x1, y1, x2, y2, score])
image = cv2.imread('w.jpg')

boxes = np.array([[5,	52,	171,	270, 0.9999],
[13,	1,	179,	268, 0.9998],
[20,	7,	176,	262, 0.8998],
[7,	5,	169,	272, 0.9687],
[3,	43,	162,	256, 0.9786],
[10,	56,	167,	266, 0.8988]])


# 将框绘制在图像上
image_for_nms_box = image.copy()
for box in boxes:
    x1, y1, x2, y2, score = int(box[0]), int(box[1]), int(box[2]), int(box[3]), box[4] # x:col y:row
    image_for_nms_box = cv2.rectangle(image_for_nms_box, (x1, y1), (x2, y2), (0,255,0), 2)
cv2.imwrite("w_all.jpg", image_for_nms_box)
cv2.imshow('w_all', image_for_nms_box)

# 使用soft_nms对框进行筛选
keep = soft_nms(boxes)
soft_nms_boxs = boxes[keep]

# 将筛选过后的框绘制在图像上
image_for_nms_box = image.copy()
for box in soft_nms_boxs:
    x1, y1, x2, y2, score = int(box[0]), int(box[1]), int(box[2]), int(box[3]), box[4]
    image_for_nms_box = cv2.rectangle(image_for_nms_box, (x1, y1), (x2, y2), (0,255,0), 2)
# Syntax: cv2.imwrite(filename, image)
cv2.imwrite("w_soft_nms.jpg", image_for_nms_box)
cv2.imshow('w_soft_nms', image_for_nms_box)

cv2.waitKey()
cv2.destroyAllWindows()


soft_nms前后对比图

before:
before2
after:
after2

nms和soft_nms效果对比图

nms:
nms效果
soft_nmssoft_nms效果

原图

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值