NMS(Non-Maximum Suppression)是计算机视觉中常用的一种技术,用于处理目标检测任务中的重叠边界框问题。下面是一个简单的NMS算法实现,它使用了C++和OpenCV库:
#include <opencv2/opencv.hpp>
#include <vector>
#include <algorithm>
void nms(std::vector<cv::Rect>& input_boxes, float threshold, std::vector<cv::Rect>& output_boxes)
{
std::sort(input_boxes.begin(), input_boxes.end(), [](const cv::Rect& a, const cv::Rect& b)
{
return a.area() > b.area();
});
while (input_boxes.size() > 0)
{
cv::Rect box1 = input_boxes[0];
output_boxes.push_back(box1);
input_boxes.erase(input_boxes.begin());
for (auto it = input_boxes.begin(); it != input_boxes.end(); )
{
cv::Rect box2 = *it;
float iou = (box1 & box2).area() / (float)(box1.area() + box2.area() - (box1 & box2).area());
if (iou > threshold)
it = input_boxes.erase(it);
else
++it;
}
}
}
在这个函数中,我们首先按照面积大小对输入的边界框进行排序。然后我们每次取出面积最大的边界框,并将其添加到输出的边界框列表中。接着我们将这个边界框从输入的边界框列表中移除,并删除与其重叠率超过阈值的所有其他边界框。这个过程将一直持续,直到输入的边界框列表为空。
注意的是,这个函数中的「iou」(Intersection over Union)计算的是两个边界框的重叠率,它是重叠区域的面积除以两个边界框的并集面积。我们使用这个值来判断两个边界框是否重叠:如果「iou」超过了阈值,我们就认为两个边界框重叠。
最后,你需要在实际的目标检测任务中,根据任务的具体需求来选择合适的阈值。