Why OpenCV has no specialize data structure for region?

后端 未结 1 1019
时光说笑
时光说笑 2021-01-07 09:30

I have been using MVTec\'s Halcon Image Processing Library for half a year and OpenCV for 1 year.

1. One thing I found that Halcon much outperforms OpenCV i

相关标签:
1条回答
  • 2021-01-07 10:00

    A common approach to represent regions is to use a Mat1i (aka a Mat of type CV_32S) that contains the indices of the regions, i.e. the labels.

    You can then access the i-th region simply with: Mat1b region_mask = (labels == i);

    With OpenCV < 3.0, you can use findConturs and drawContours to create the labels image:

    #include <opencv2\opencv.hpp>
    #include <vector>
    using namespace cv;
    using namespace std;
    
    int main()
    {
        // Read image from file 
        Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);
    
        Mat1b region;
        threshold(img, region, 200, 255, THRESH_BINARY);
    
        vector<vector<Point>> contours;
        findContours(region.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
    
        Mat1i labels(img.rows, img.cols, int(0));
        int n_labels = contours.size();
    
        for (int i = 0; i < contours.size(); ++i)
        {
            drawContours(labels, contours, i, Scalar(i + 1), CV_FILLED); // Note the +1, since 0 is the background
        }
    
        // Now you can get your regiones as:
    
        // Label "0" is the background
        for (int i = 1; i <= n_labels; ++i)
        {
            Mat1b region_mask = (labels == i);
            imshow("Region", region_mask);
            waitKey();
        }
    
        return 0;
    }
    

    With OpenCV >= 3.0 you can use connectedComponents, which will directly return the labels:

    #include <opencv2\opencv.hpp>
    #include <vector>
    using namespace cv;
    using namespace std;
    
    int main()
    {
        // Read image from file 
        Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);
    
        Mat1b region;
        threshold(img, region, 200, 255, THRESH_BINARY);
    
        Mat1i labels;
        int n_labels = connectedComponents(region, labels);
    
        // Now you can get your regiones as:
    
        // Label "0" is the background
        for (int i = 1; i <= n_labels; ++i)
        {
            Mat1b region_mask = (labels == i);
            imshow("Region", region_mask);
            waitKey();
        }
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题