opencv find perimeter of a connected component

后端 未结 2 426
一个人的身影
一个人的身影 2021-01-26 00:47

I\'m using opencv 2.4.13

I\'m trying to find the perimeter of a connected component, I was thinking of using ConnectedComponentWithStats but it doesn\'t return the perim

相关标签:
2条回答
  • 2021-01-26 01:23

    Adding to @Miki's answer, This is a faster way to find the perimeter of the connected component

    //getting the connected components with statistics
    cv::Mat1i labels, stats;
    cv::Mat centroids;
    
    int lab = connectedComponentsWithStats(img, labels, stats, centroids);
    
    for (int i = 1; i < lab; ++i)
    {
        //Rectangle around the connected component
        cv::Rect rect(stats(i, 0), stats(i, 1), stats(i, 2), stats(i, 3));
    
        // Get the mask for the i-th contour
        Mat1b mask_i = labels(rect) == i;
    
        // Compute the contour
        vector<vector<Point>> contours;     
        findContours(mask_i, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
    
        if(contours.size() <= 0)
             continue;        
    
        //Finding the perimeter
        double perimeter = contours[0].size();
        //you can use this as well for measuring perimeter
        //double perimeter = arcLength(contours[0], true);
    
    }
    
    0 讨论(0)
  • 2021-01-26 01:25

    The easiest thing is probably to use findContours.

    You can compute the contour on the i-th component computed by connectedComponents(WithStats) , so they are aligned with your labels. Using CHAIN_APPROX_NONE you'll get all the points in the contour, so the size() of the vector is already a measure of the perimeter. You can eventually use arcLength(...) to get a more accurate result:

    Mat1i labels;
    int n_labels = connectedComponents(img, labels);
    
    for (int i = 1; i < n_labels; ++i)
    {
        // Get the mask for the i-th contour
        Mat1b mask_i = labels == i;
    
        // Compute the contour
        vector<vector<Point>> contours;     
        findContours(mask_i.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
    
        if (!contours.empty())
        {
            // The first contour (and probably the only one)
            // is the one you're looking for
    
            // Compute the perimeter
            double perimeter_i = contours[0].size();
        }
    }
    
    0 讨论(0)
提交回复
热议问题