NMS(非极大值抑制)实现

在目标检测算法中,为了尽量不漏掉物体,会输出大量的检测结果(每一条结果由检测概率与检测框组成)。这些检测结果很可能有重复的,即会有多个框标出了同一个物体。
我们需要一个算法来过滤多余的检测框。最常用的算法就是NMS(Non-Maximum Suppresion, 非极大值抑制)。该算法的思路很简单:只保留局部概率最大的检测框,与其重合的其他检测框都会被舍去。

算法的伪代码如下:

输入所有检测概率、检测框
当还有检测框没有处理:
    从剩下的框里挑出检测概率最大的框 bbox_a
    遍历所有没有处理的框bbox_i:
        如果 bbox_i != bbox_a 且 bbox_i 与 bbox_a 重合:
            舍去 bbox_i
    把 bbox_a 输出成一个检测结果

当然,这个算法的描述还不够准确:究竟该怎么定义两个检测框是“重合”呢?如果两个检测框有交集就说它们重合是行不通的,因为图片中很可能会有挨得很近的物体,它们的检测框就是相交的。因此,我们一般用IoU(交并比)来描述两个框的重合程度,如果IoU超出某个阈值,就说这两个框是“重合”的。

IoU的计算很简单,算出两个矩形的「交面积」,再用两个矩形面积之和减去「交面积」就可以得到「并面积」,「交面积」比「并面积」就是IoU。
在这里插入图片描述

python实现:

import numpy as np


def NMSBoxes(input, score_threshold, nms_threshold):
    boxes = input[input[:, 4] > score_threshold] # score_threshold过滤

    x1 = boxes[:, 0] - boxes[:, 2] * 0.5
    y1 = boxes[:, 1] - boxes[:, 3] * 0.5
    x2 = boxes[:, 0] + boxes[:, 2] * 0.5
    y2 = boxes[:, 1] + boxes[:, 3] * 0.5

    scores = boxes[:, 4]
    areas = (x2-x1) * (y2-y1)
    results = []

    index = np.argsort(scores)[::-1]     # 按置信度进行排序

    while(index.size):
        # 置信度最高的框
        i = index[0]
        results.append(index[0])

        if(index.size == 1): # 如果只剩一个框,直接返回
            break

        # 计算交集左下角与右上角坐标
        inter_x1 = np.maximum(x1[i], x1[index[1:]])
        inter_y1 = np.maximum(y1[i], y1[index[1:]])
        inter_x2 = np.minimum(x2[i], x2[index[1:]])
        inter_y2 = np.minimum(y2[i], y2[index[1:]])

        # 计算交集的面积
        w = np.maximum(inter_x2 - inter_x1, 0) 
        h = np.maximum(inter_y2 - inter_y1, 0)
        inter_area = w * h
        
        # 计算当前框与其余框的iou
        iou = inter_area / (areas[index[1:]] + areas[i] - inter_area)
        id = np.where(iou < nms_threshold)[0]
        index = index[id + 1]

    return input[results]


if __name__ == '__main__':
    boxes = np.array([[1,1,3,3,0.6], [0,0,2,2,0.7], [0,0,2,2,0.2]])
    res = NMSBoxes(input=boxes, score_threshold=0.5, nms_threshold=0.2)
    print(res)

C++实现:

#include <iostream>
#include <vector>
#include <algorithm>


typedef struct Bbox
{
	float x;
	float y;
	float w;
	float h;
	float score;
}Bbox;


void printboxes(std::vector<Bbox> boxes)
{
	for (size_t i = 0; i < boxes.size(); i++)
	{
		printf("%f %f %f %f %f \n", boxes[i].x, boxes[i].y, boxes[i].w, boxes[i].h, boxes[i].score);
	}
	printf("\n");
}


float iou(Bbox box1, Bbox box2)
{
	float x1 = std::max(box1.x - box1.w * 0.5, box2.x - box2.w * 0.5);
	float y1 = std::max(box1.y - box1.h * 0.5, box2.y - box2.h * 0.5);
	float x2 = std::min(box1.x + box1.w * 0.5, box2.x + box2.w * 0.5);
	float y2 = std::min(box1.y + box1.h * 0.5, box2.y + box2.h * 0.5);
	float w = std::max(0.0f, x2 - x1);
	float h = std::max(0.0f, y2 - y1);
	float inter_area = w * h;
	float iou = inter_area / (box1.w * box1.h + box2.w * box2.h - inter_area);

	return iou;
}


std::vector<Bbox> NMSBoxes(std::vector<Bbox> & boxes, float score_threshold, float nms_threshold)
{
	std::vector<Bbox> boxes_results;
	std::sort(boxes.begin(), boxes.end(), [](Bbox box1, Bbox box2) {return box1.score > box2.score; }); //将box按照score从高到低排序

	//score_threshold过滤
	for (size_t i = 0; i < boxes.size(); i++)
	{
		if (boxes[i].score < score_threshold)
			boxes.erase(boxes.begin() + i);
		else
			i++;
	}
	//printboxes(boxes);

	while (boxes.size() > 0)
	{
		boxes_results.push_back(boxes[0]);
		int index = 1;
		//计算最大score对应的box与剩下所有的box的IOU,移除所有大于IOU阈值的box
		while (index < boxes.size())
		{
			float iou_value = iou(boxes[0], boxes[index]);
			//std::cout << iou_value << std::endl;

			if (iou_value > nms_threshold)
				boxes.erase(boxes.begin() + index);
			else
				index++;
		}
		boxes.erase(boxes.begin()); //results已经保存,所以可以将最大的删除了
	}

	return boxes_results;
}


int main()
{
	std::vector<Bbox> boxes = { { 1,1,3,3,0.6 }, { 0,0,2,2,0.7 }, { 0,0,2,2,0.2 } };
	std::vector<Bbox> res = NMSBoxes(boxes, 0.5, 0.2);
	printboxes(res);

	return 0;
}

下面是在杜佬的代码中学到的实现方式,更容易理解,但需要多开辟vector的大小用来标记box是否要去除:

#include <iostream>
#include <vector>
#include <algorithm>


typedef struct Bbox
{
	float x;
	float y;
	float w;
	float h;
	float score;
}Bbox;


void printboxes(std::vector<Bbox> boxes)
{
	for (size_t i = 0; i < boxes.size(); i++)
	{
		printf("%f %f %f %f %f \n", boxes[i].x, boxes[i].y, boxes[i].w, boxes[i].h, boxes[i].score);
	}
	printf("\n");
}


float iou(Bbox box1, Bbox box2)
{
	float x1 = std::max(box1.x - box1.w * 0.5, box2.x - box2.w * 0.5);
	float y1 = std::max(box1.y - box1.h * 0.5, box2.y - box2.h * 0.5);
	float x2 = std::min(box1.x + box1.w * 0.5, box2.x + box2.w * 0.5);
	float y2 = std::min(box1.y + box1.h * 0.5, box2.y + box2.h * 0.5);
	float w = std::max(0.0f, x2 - x1);
	float h = std::max(0.0f, y2 - y1);
	float inter_area = w * h;
	float iou = inter_area / (box1.w * box1.h + box2.w * box2.h - inter_area);

	return iou;
}


std::vector<Bbox> NMSBoxes(std::vector<Bbox> & boxes, float score_threshold, float nms_threshold)
{
	std::vector<Bbox> boxes_results;
	std::sort(boxes.begin(), boxes.end(), [](Bbox box1, Bbox box2) {return box1.score > box2.score; }); //将box按照score从高到低排序

	//score_threshold过滤
	for (size_t i = 0; i < boxes.size(); i++)
	{
		if (boxes[i].score < score_threshold)
			boxes.erase(boxes.begin() + i);
		else
			i++;
	}
	//printboxes(boxes);

	std::vector<bool> remove_flags(boxes.size());
	for (size_t i = 0; i < boxes.size(); ++i) 
	{
		if (remove_flags[i]) 
			continue;

		boxes_results.push_back(boxes[i]);
		for (size_t j = i + 1; j < boxes.size(); ++j) 
		{
			if (remove_flags[j]) 
				continue;

			if (iou(boxes[i], boxes[j]) >= nms_threshold)
				remove_flags[j] = true;
		}
	}

	return boxes_results;
}


int main()
{
	std::vector<Bbox> boxes = { { 1,1,3,3,0.6 }, { 0,0,2,2,0.7 }, { 0,0,2,2,0.2 } };
	std::vector<Bbox> res = NMSBoxes(boxes, 0.5, 0.2);
	printboxes(res);

	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
nms非极大值抑制有以下几种方法和改进: 1. 基本的NMS方法是利用得分高的边框来抑制得分低且重叠程度高的边框。这种方法简单有效,但在更高的目标检测需求下存在一些缺点。 2. Soft NMS是一种改进的方法,它通过对重叠框的得分进行一定的衰减,而不是直接抑制掉得分低的边框。这样可以保留一些得分低但可能是真正目标的边框。 3. Softer NMS是Soft NMS的进一步改进,它在计算重叠框的得分衰减时引入了一个可学习的参数。这个参数可以根据具体的数据进行优化,从而更加灵活地调整得分衰减的方式。 4. Adaptive NMS是根据物体密集程度自适应调整NMS阈值的方法。它通过使用卷积神经网络(CNN)来判断人群的密集程度,并根据密集程度决定NMS阈值的大小。 5. IoUNet是一种基于IoU(Intersection over Union)的方法,它通过训练一个神经网络来预测边框之间的IoU值。然后,根据IoU值来判断是否进行非极大值抑制。 综上所述,nms非极大值抑制有基本的NMS方法、Soft NMS、Softer NMS、Adaptive NMS和IoUNet等不同的方法和改进。每种方法都有其特点和适用场景,可以根据具体需求选择合适的方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【目标检测系列】非极大值抑制(NMS)的各类变体汇总](https://blog.csdn.net/weixin_47196664/article/details/106754955)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

给算法爸爸上香

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

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

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

打赏作者

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

抵扣说明:

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

余额充值