How to find the largest contour?

2020-06-28 05:10发布

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)

2条回答
何必那么认真
2楼-- · 2020-06-28 05:30

I assume the collection is a nested vector of points according to what findContours function from OpenCV requires.

In such case you can see an example of the solution: Find Biggest Contour Using C++

Basically you call contourArea to acquire the actual area taken by the contour, or boundingRect alternatively minAreaRect to determine the area a contour can be enclosed with. Depends on what you actually require.

查看更多
Luminary・发光体
3楼-- · 2020-06-28 05:45

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(),
                           contours.end(),
                           [](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.

查看更多
登录 后发表回答