【问题标题】:OpenCV HoughCircles detecting only 1 circleOpenCV HoughCircles 仅检测 1 个圆圈
【发布时间】:2020-04-22 08:39:47
【问题描述】:

我正在尝试检测、定位和拾取蓝色弹珠。 我的项目的目的是一次只检测 1 个弹珠。 对于我的检测,我使用的是 OpenCV 的 HoughCircles 函数。我想代码只给我第一个检测到的圆的 X 和 Y 位置。

这是我为此使用的代码:

vector<Vec3f> circles;
HoughCircles(OutputImage, circles, HOUGH_GRADIENT, 1,
    OutputImage.rows / rows,      //change to detect circles that are closer to eachother
    para1, para2, minRad, maxRad);        //chang last to parameters to detect larger or smaller circles


for (size_t i = 0; i < circles.size(); i++)
{
    Vec3i c = circles[i];
    Point center = Point(c[0], c[1]);
    // circle center
    circle(imgHSV, center, 1, Scalar(0, 255, 0), 3, LINE_AA);
    // circle outline
    int radius = c[2];
    circle(imgHSV, center, radius, Scalar(255, 0, 0), 3, LINE_AA);

    cout << "The center of the detection is located at pixel: " << Point(c[0], c[1]) << endl;

    x = c[0];
    y = c[1];


}

但是,这仍然会检测所有圆圈并打印出所有圆圈的 X、Y 信息。 我尝试在 for 循环中将 circles.size() 更改为 1 但这给了我以下错误: Expression: vector subscript out of range

这里有人能帮助我吗,这是我的第一个 OpenCV 应用程序,如果我误解了,请见谅。

如果您需要我的完整代码,请随时询问。

【问题讨论】:

    标签: c++ opencv


    【解决方案1】:

    方法HoughCircles给你所有找到的圈子:

    要访问“第一个”圈子,您需要这样做:

    if(circles.size() > 0) {
        Vec3i c = circles.at(0);
        Point center = Point(c[0], c[1]);
        // circle center
        circle(imgHSV, center, 1, Scalar(0, 255, 0), 3, LINE_AA);
        // circle outline
        int radius = c[2];
        circle(imgHSV, center, radius, Scalar(255, 0, 0), 3, LINE_AA);
    
        cout << "The center of the detection is located at pixel: " << Point(c[0], c[1]) << endl;
    
        x = c[0];
        y = c[1];
    }
    

    但在我看来,您的问题是,您不了解您编写的 C++ 代码...

    【讨论】:

    • 感谢您的回答,这修复了我的代码。我对 C++ 编码仍然相当陌生,并且正在尝试通过反复试验来学习,所以这可能是我应该已经理解的一个基本问题。但现在我知道了,所以谢谢你!
    • 如果您是编码新手,我认为从 OpenCV 开始不是一个好主意。首先学习 C++ 的基础知识
    【解决方案2】:

    好吧,无论 HoughCircles() 找到多少个圆圈,圆圈都会包含。 WH 可能 >=0。

    for{} 循环遍历圆圈并报告每个圆圈的详细信息。所以基本上你可以打破;跳出循环。 即

    for (size_t i = 0; i < circles.size(); i++)
    {
         ...
         break; /// i think this works in c++
    }
    

    或更改 for 循环以进行简单的条件检查

    if (circles.size() > 0)
    {
       Vec3i c = circles[0];
       ...
    }
    

    【讨论】:

    • 就像其他答案一样,这修复了我的代码。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多