【发布时间】:2016-09-22 04:06:31
【问题描述】:
由于现在是我的学校假期,我决定学习一些技能,因此我正在尝试学习如何使用 Visual Studio C++ 的 OpenCV 功能来检测纸箱中有多少罐头,并且必须将其按 4 分组4.
我尝试了各种演示代码,例如“opencv find:contour”、模板匹配(效果不佳,因为它无法检测到顶盖的旋转)
我发现最好的方法是将Canny Edge Detection和Hough Transform Circle结合起来,Canny Edge Detection的输出结果可以是Hough Transform Circle的输入图像,结果如下。
不幸的是,不是所有的圆圈都被检测到,如果我改变了
for (int i = 0; i < circles.size(); i++)进入
for (int i = 0; i < 24; i++) // 24 is the no. of cans
我会得到一个表达式:向量下标超出范围。我不知道为什么它只能检测到 21 个圆圈
源码如下:-
using namespace cv;
using namespace std;
Mat src, src_gray;
int main()
{
Mat src1;
src1 = imread("cans.jpg", CV_LOAD_IMAGE_COLOR);
namedWindow("Original image", CV_WINDOW_AUTOSIZE);
imshow("Original image", src1);
Mat gray, edge, draw;
cvtColor(src1, gray, CV_BGR2GRAY);
Canny(gray, edge,50, 150, 3);
//50,150,3
edge.convertTo(draw, CV_8U);
namedWindow("Canny Edge", CV_WINDOW_AUTOSIZE);
imshow("Canny Edge", draw);
imwrite("output.jpg", draw);
waitKey(500);
/// Read the image
src = imread("output.jpg", 1);
Size size(932, 558);//the dst image size,e.g.100x100
resize(src, src, size);//resize image
/// Convert it to gray
cvtColor(src, src_gray, CV_BGR2GRAY);
/// Reduce the noise so we avoid false circle detection
GaussianBlur(src_gray, src_gray, Size(9, 9), 2, 2);
vector<Vec3f> circles;
/// Apply the Hough Transform to find the circles
HoughCircles(src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows / 8,200, 100, 0, 0);
/// Draw the circles detected
for (int i = 0; i < circles.size(); i++)
{
printf("are you um?\n");
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// circle center
circle(src, center, 3, Scalar(0, 255, 0), -1, 8, 0);
// circle outline
circle(src, center, radius, Scalar(255, 0, 255), 3, 8, 0);
}
// namedWindow("Hough Circle Transform Demo", CV_WINDOW_NORMAL);
imshow("Hough Circle Transform Demo", src);
line(src, Point(0, 288), Point(1024, 288), Scalar(225, 220, 225), 2, 8);
// middle line
line(src, Point(360, 0), Point(360, 576), Scalar(225, 220, 225), 2, 8);
//break cans into 4 by 4
line(src, Point(600, 0), Point(600, 576), Scalar(225, 220, 225), 2, 8);
// x, y
imshow("Lines", src);
imwrite("lineoutput.jpg", src);
waitKey(0);
return 0;
}
我还手动输入了线条的坐标,将它们分组为 4 x 4。 我应该更改什么以使其没有任何下标超出范围错误并能够检测到所有圆圈?
【问题讨论】:
-
您无法访问比您找到的更多内容。它找到了 21 个圆,因此该向量包含 21 个圆。如果将循环变量更改为 24,则会出现下标错误,因为向量大小为 21。您无法访问超过其大小的内容。要获取缺少的圈子,您可以从程序中添加圈子。它并不总是有效,但在某种程度上它会有效。它就像一个 6x4 的网格。从中心距离,您可以轻松假设缺少哪些圆圈.....
-
我不认为我会手动添加圆圈,因为我得到了 10 多张具有不同照明和位置的图像。谢谢!修复了下标错误,我的 6x4 网格可能只是为了展示,因为它什么都不做:l
标签: c++ visual-studio opencv hough-transform canny-operator