如何找到最大的轮廓

How to find the largest contour?

本文关键字:轮廓 何找      更新时间:2023-10-16

我已经在 python 中写了一个脚本,该使用 max> max> max()方法,我正在尝试在C 中重新创建类似程序但是我很难获得面具中最大轮廓的值。

我尝试使用c 算法库中的 max_element()函数,但无济于事。我还试图解释迭代器,但会收到一系列错误,这是我的代码:

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

这是错误:

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

这是我在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)

在您的python示例中,您将比较器作为 key参数

传递给比较器
c = max(contours, key = cv2.contourArea)

这样做的等同于将比较器传递给std::max_element以及

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);
          });

在这种情况下, c将为std::vector<cv::Point>类型,代表轮廓。

我假设该集合是根据openCV的 findContours函数的嵌套向量。

在这种情况下,您可以看到解决方案的示例:使用C

查找最大轮廓

基本上,您致电contourArea获取轮廓所取的实际面积,或者boundingRectminAreaRect以确定可以包含轮廓的区域。取决于您实际需要的。