OpenCV:合并重叠的矩形

mar*_*man 5 c++ opencv bounding-box object-detection

在使用 OpenCV 进行检测任务时,我一直遇到合并重叠边界框的问题;也就是说,本质上是在两个重叠边界框的并集​​周围找到边界框。当出于某种原因感兴趣的对象被分解为多个边界框,而不是一个包罗万象的边界框时,这在对象检测中会出现很多。

StackOverflow 上有一些关于算法解决方案和有用的外部库(例如thisthisthis)的答案,还有groupRectanglesOpenCV 提供的函数(以及一连串相关问题/错误:thisthis等)。

我似乎发现上述解决方案对于我尝试执行的任务来说有点过于复杂。许多算法解决方案从数学的角度解决了这个问题(更像是一个思想实验),而rect1 | rect2当矩形的数量很高(处理所有事情的时间是 O(N^2))并且groupRectangles有一些使其仅部分有效的怪癖。所以我想出了一个有点骇人听闻的解决方案,它实际上非常有效。我想我会在下面分享给需要快速解决这个常见问题的其他人。

随意评论和批评它。

mar*_*man 2

void mergeOverlappingBoxes(std::vector<cv::Rect> &inputBoxes, cv::Mat &image, std::vector<cv::Rect> &outputBoxes)
{
    cv::Mat mask = cv::Mat::zeros(image.size(), CV_8UC1); // Mask of original image
    cv::Size scaleFactor(10,10); // To expand rectangles, i.e. increase sensitivity to nearby rectangles. Doesn't have to be (10,10)--can be anything
    for (int i = 0; i < inputBoxes.size(); i++)
    {
        cv::Rect box = inputBoxes.at(i) + scaleFactor;
        cv::rectangle(mask, box, cv::Scalar(255), CV_FILLED); // Draw filled bounding boxes on mask
    }

    std::vector<std::vector<cv::Point>> contours;
    // Find contours in mask
    // If bounding boxes overlap, they will be joined by this function call
    cv::findContours(mask, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
    for (int j = 0; j < contours.size(); j++)
    {
        outputBoxes.push_back(cv::boundingRect(contours.at(j)));
    }
}
Run Code Online (Sandbox Code Playgroud)