OpenCV C++: Sorting contours by their contourArea

前端 未结 2 1372
迷失自我
迷失自我 2020-12-08 17:41

How can I sort contours by the size of their contour areas? And how can I get the biggest/smallest one?

2条回答
  •  时光取名叫无心
    2020-12-08 17:52

    You can use std::sort with a custom comparison function object

    // comparison function object
    bool compareContourAreas ( std::vector contour1, std::vector contour2 ) {
        double i = fabs( contourArea(cv::Mat(contour1)) );
        double j = fabs( contourArea(cv::Mat(contour2)) );
        return ( i < j );
    }
    

    Usage:

    [...]
    
    // find contours
    std::vector > contours;
    std::vector hierarchy;
    cv::findContours( binary_image, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
    
    // sort contours
    std::sort(contours.begin(), contours.end(), compareContourAreas);
    
    // grab contours
    std::vector biggestContour = contours[contours.size()-1];
    std::vector smallestContour = contours[0];
    

提交回复
热议问题