Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV C++: Sorting contours by their contourArea

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

like image 845
dom Avatar asked Nov 21 '12 14:11

dom


People also ask

How do you sort contours in OpenCV?

The actual sort_contours function is defined on Line 7 and takes two arguments. The first is cnts , the list of contours that the we want to sort, and the second is the sorting method , which indicates the direction in which we are going to sort our contours (i.e. left-to-right, top-to-bottom, etc.).

What is cv2 approxPolyDP?

Working of approxPolyDP() function in OpenCV We make use of a function in OpenCV called approxPolyDP() function to perform an approximation of a shape of a contour. The image of a polygon whose shape of a contour must be approximated is read using the imread() function.


Video Answer


2 Answers

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];
like image 81
dom Avatar answered Oct 07 '22 04:10

dom


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.

like image 39
xmfbit Avatar answered Oct 07 '22 03:10

xmfbit