OpenCV C++: Sorting contours by their contourArea

烂漫一生 提交于 2019-11-27 12:30:04

问题


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


回答1:


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

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

Usage:

[...]

// find contours
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> 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<cv::Point> biggestContour = contours[contours.size()-1];
std::vector<cv::Point> smallestContour = contours[0];



回答2:


Just give a solution using the lambda function if C++11 is available.

    sort(contours.begin(), contours.end(), [](const vector<Point>& c1, const vector<Point>& c2){
    return contourArea(c1, false) < contourArea(c2, false);
});

Then you can access contours[0] to get the contour with the smallest area and contours[contours.size()-1] to get the one with the largest area because the contours are sorted in ascending order.



来源:https://stackoverflow.com/questions/13495207/opencv-c-sorting-contours-by-their-contourarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!