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)
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, orboundingRect
alternativelyminAreaRect
to determine the area a contour can be enclosed with. Depends on what you actually require.In your Python example you are passing a comparator as the
key
argumentThe equivalent of doing this is to pass a comparator to
std::max_element
as wellIn this case
c
will be of typestd::vector<cv::Point>
which represents a contour.