我正在尝试检测、定位和拾取蓝色弹珠。我的项目的目标是一次只能探测一块大理石。为了进行检测,我使用了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应用程序,如果我误解了,很抱歉。
如果您需要我的完整代码,请随时询问。
发布于 2020-04-22 16:52:18
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++代码……
发布于 2020-04-22 16:53:44
嗯,无论HoughCircles()找到多少个圆,圆都会包含其中。WHich可能是>=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];
...
}
https://stackoverflow.com/questions/61360787
复制相似问题