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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With