randy sandy randy sandy - 8 months ago 48
C++ Question

How to find the largest contour?

I have written a script in python that utilises the max() method, I am trying to recreate a similar program in c++ but I am having trouble obtaining the value for the largest contour in a mask.

I have tried to use the max_element() function from the algorithm library in C++ but to no avail. I have also tried to dereference the iterator but receive a series of errors, here is my code:

if (contours.size() > 0)
c = *max_element(contours.begin(), contours.end());
//not compiling

Here is the error:

no match for 'operator=' (operand types are 'std::vector<std::vector<cv::Point_<int> > >' and 'std::vector<cv::Point_<int> >')

Here is how I do it in Python:

if len(contours) > 0;
#find largest contour in mask, use to compute minEnCircle
c = max(contours, key = cv2.contourArea)
(x,y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)

Answer Source

In your Python example you are passing a comparator as the key argument

c = max(contours, key = cv2.contourArea)

The equivalent of doing this is to pass a comparator to std::max_element as well

auto c = *std::max_element(contours.begin(),
                           [](std::vector<cv::Point> const& lhs, std::vector<cv::Point> const& rhs)
              return contourArea(lhs, false) < contourArea(rhs, false);

In this case c will be of type std::vector<cv::Point> which represents a contour.

(It's been a while since I've used OpenCV so please excuse mistakes in any of their functions or typenames)