如何找到最大的轮廓? [英] How to find the largest contour?

查看:168
本文介绍了如何找到最大的轮廓?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 python 中编写了一个脚本,该脚本利用了 max()方法,我试图在c ++中重新创建类似的程序,但是我在获取值时遇到了麻烦遮罩中最大的轮廓.

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.

我尝试使用C ++算法库中的 max_element()函数,但无济于事.我也尝试过取消对迭代器的引用,但是收到一系列错误,这是我的代码:

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
}

这是错误:

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

这是我在Python中执行的操作:

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)

推荐答案

在您的Python示例中,您正在传递一个比较器作为key参数

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

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

等效的方法是也将比较器传递给std::max_element

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

在这种情况下,c将是表示轮廓的std::vector<cv::Point>类型.

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

这篇关于如何找到最大的轮廓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆