在OpenCV中,将相邻的白色像素聚集在一起,并在它们周围画一个矩形。

5
我想在使用C++的OpenCV中,将彼此更接近的白色像素分组并在其周围绘制矩形。
原始图像: 期望结果: 我对OpenCV不熟悉。任何帮助都将不胜感激。
2个回答

7
你可以使用partition根据给定谓词将白色像素分组。在这种情况下,您的谓词可以是:将所有在给定欧几里得距离内的白色像素分组
然后,您可以计算每个组的边界框,保留最大的框(在下面的红色框中),并最终扩大它(在下面的绿色框中):

enter image description here

代码:

#include <opencv2\opencv.hpp>
#include <vector>
#include <algorithm>

using namespace std;
using namespace cv;

int main()
{
    // Load the image 
    Mat3b img = imread("path_to_image", IMREAD_COLOR);

    // Convert to grayscale
    Mat1b gray;
    cvtColor(img, gray, COLOR_BGR2GRAY);

    // Get binary mask (remove jpeg artifacts)
    gray = gray > 200;

    // Get all non black points
    vector<Point> pts;
    findNonZero(gray, pts);

    // Define the radius tolerance
    int th_distance = 50; // radius tolerance

    // Apply partition 
    // All pixels within the radius tolerance distance will belong to the same class (same label)
    vector<int> labels;

    // With lambda function (require C++11)
    int th2 = th_distance * th_distance;
    int n_labels = partition(pts, labels, [th2](const Point& lhs, const Point& rhs) {
        return ((lhs.x - rhs.x)*(lhs.x - rhs.x) + (lhs.y - rhs.y)*(lhs.y - rhs.y)) < th2;
    });

    // You can save all points in the same class in a vector (one for each class), just like findContours
    vector<vector<Point>> contours(n_labels);
    for (int i = 0; i < pts.size(); ++i)
    {
        contours[labels[i]].push_back(pts[i]);
    }

    // Get bounding boxes
    vector<Rect> boxes;
    for (int i = 0; i < contours.size(); ++i)
    {
        Rect box = boundingRect(contours[i]);
        boxes.push_back(box);
    }

    // Get largest bounding box
    Rect largest_box = *max_element(boxes.begin(), boxes.end(), [](const Rect& lhs, const Rect& rhs) {
        return lhs.area() < rhs.area();
    });

    // Draw largest bounding box in RED
    Mat3b res = img.clone();
    rectangle(res, largest_box, Scalar(0, 0, 255));

    // Draw enlarged BOX in GREEN
    Rect enlarged_box = largest_box + Size(20,20);
    enlarged_box -= Point(10,10);

    rectangle(res, enlarged_box, Scalar(0, 255, 0));


    imshow("Result", res);
    waitKey();

    return 0;
}

非常感谢 @Miki。这段代码真的很有帮助,易于理解。 - Ilakkiya
@Miki 有没有办法找出绘制的边界框的中心坐标? - Ilakkiya
@Miki @Ilakkiya 我正在使用同样的方法,但是在 Get largest bounding box 处我遇到了(一种异常 : Access violation reading location ) 错误。 - Krupali Mistry
@KrupaliMistry 检查向量是否为空 - Miki
@Miki 是的,我已经检查过了并且得到了它!!谢谢。 - Krupali Mistry

-1

谢谢您的建议@bercik。您能否发布一个关于积分部分的示例代码? - Ilakkiya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接