转:非极大值抑制(Non-Maximum Suppression,NMS)

非极大值抑制(Non-Maximum Suppression,NMS)

单类别NMS的numpy实现

    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]

        kept_bboxes = [] #保留的结果框集合
        while order.size > 0:
            i = order[0]
            kept_bboxes.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 kept_bboxes

  

单类别NMS的pytorch实现

    def _nms(self, bboxes, scores, threshold=0.5):
        x1 = bboxes[:,0]
        y1 = bboxes[:,1]
        x2 = bboxes[:,2]
        y2 = bboxes[:,3]
        areas = (x2-x1)*(y2-y1)   # [N,] 每个bbox的面积
        _, order = scores.sort(0, descending=True)    # 降序排列

        kept_bboxes = []
        while order.numel() > 0:       # torch.numel()返回张量元素个数
            if order.numel() == 1:     # 保留框只剩一个
                i = order.item()
                kept_bboxes.append(i)
                break
            else:
                i = order[0].item()    # 保留scores最大的那个框box[i]
                kept_bboxes.append(i)

            # 计算box[i]与其余各框的IOU(思路很好)
            xx1 = x1[order[1:]].clamp(min=x1[i])   # [N-1,]
            yy1 = y1[order[1:]].clamp(min=y1[i])
            xx2 = x2[order[1:]].clamp(max=x2[i])
            yy2 = y2[order[1:]].clamp(max=y2[i])
            inter = (xx2-xx1).clamp(min=0) * (yy2-yy1).clamp(min=0)   # [N-1,]

            iou = inter / (areas[i]+areas[order[1:]]-inter)  # [N-1,]
            idx = (iou <= threshold).nonzero().squeeze() # 注意此时idx为[N-1,] 而order为[N,]
            if idx.numel() == 0:
                break
            order = order[idx+1]  # 修补索引之间的差值
        return torch.LongTensor(kept_bboxes)   # Pytorch的索引值为LongTensor

  

posted @ 2021-05-23 16:01  Picassooo  阅读(80)  评论(0编辑  收藏  举报