在本教程中,您将学习如何:
在线路检测情况下,一条线路由两个参数 (r,Q)定义。在圆的情况下,我们需要三个参数来定义一个圆:
其中 (xcenter,ycenter)定义中心位置(绿点,),r是半径,这让我们可以完全定义一个圆,如下图所示:
我们将要解释的示例代码可以从这里下载。可以在此处找到一个稍微花哨的版本(显示用于更改阈值的跟踪栏)。
- #include "opencv2/imgcodecs.hpp"
- #include "opencv2/highgui.hpp"
- #include "opencv2/imgproc.hpp"
-
- using namespace cv;
- using namespace std;
-
- int main(int argc, char** argv)
- {
- const char* filename = argc >=2 ? argv[1] : "smarties.png";
-
- // Loads an image
- Mat src = imread( samples::findFile( filename ), IMREAD_COLOR );
-
- // Check if image is loaded fine
- if(src.empty()){
- printf(" Error opening image\n");
- printf(" Program Arguments: [image_name -- default %s] \n", filename);
- return EXIT_FAILURE;
- }
-
- Mat gray;
- cvtColor(src, gray, COLOR_BGR2GRAY);
-
- medianBlur(gray, gray, 5);
-
- vector
circles; - HoughCircles(gray, circles, HOUGH_GRADIENT, 1,
- gray.rows/16, // change this value to detect circles with different distances to each other
- 100, 30, 1, 30 // change the last two parameters
- // (min_radius & max_radius) to detect larger circles
- );
-
- for( size_t i = 0; i < circles.size(); i++ )
- {
- Vec3i c = circles[i];
- Point center = Point(c[0], c[1]);
- // circle center
- circle( src, center, 1, Scalar(0,100,100), 3, LINE_AA);
- // circle outline
- int radius = c[2];
- circle( src, center, radius, Scalar(255,0,255), 3, LINE_AA);
- }
-
- imshow("detected circles", src);
- waitKey();
-
- return EXIT_SUCCESS;
- }
我们使用的图像可以在这里找到
- const char* filename = argc >=2 ? argv[1] : "smarties.png";
-
- // Loads an image
- Mat src = imread( samples::findFile( filename ), IMREAD_COLOR );
-
- // Check if image is loaded fine
- if(src.empty()){
- printf(" Error opening image\n");
- printf(" Program Arguments: [image_name -- default %s] \n", filename);
- return EXIT_FAILURE;
- }
- Mat gray;
- cvtColor(src, gray, COLOR_BGR2GRAY);
medianBlur(gray, gray, 5);
- vector
circles; - HoughCircles(gray, circles, HOUGH_GRADIENT, 1,
- gray.rows/16, // change this value to detect circles with different distances to each other
- 100, 30, 1, 30 // change the last two parameters
- // (min_radius & max_radius) to detect larger circles
- );
- for( size_t i = 0; i < circles.size(); i++ )
- {
- Vec3i c = circles[i];
- Point center = Point(c[0], c[1]);
- // circle center
- circle( src, center, 1, Scalar(0,100,100), 3, LINE_AA);
- // circle outline
- int radius = c[2];
- circle( src, center, radius, Scalar(255,0,255), 3, LINE_AA);
- }
你可以看到,我们将用红色画圆圈,用一个小绿点画中心
- imshow("detected circles", src);
- waitKey();
使用测试图像运行上述代码的结果如下所示:
参考文献:
1、《Hough Circle Transform》------Ana Huamán