OpenCV HoughCircles只检测到1个圆。

问题描述 投票:0回答:2

我正在尝试检测和定位并拾取蓝色弹珠,我的项目的目的是一次只检测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信息。circles.size()1 的for循环中,但这给了我以下错误。Expression: vector subscript out of range(向量下标超出范围)

这里有谁能帮助我,这是我的第一个OpenCV应用程序,如果我理解错了,对不起。

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

c++ opencv
2个回答
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++代码... ...


0
投票

好吧,无论HoughCircles()找到多少个圆,circle都会包含。其中可以是>=0。

for{}循环是在圆圈中循环,并报告每个圆圈的细节。因此,基本上你可以将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];
   ...
}
© www.soinside.com 2019 - 2024. All rights reserved.