samples/cpp/tutorial_code/ImgTrans/houghcircles.cpp#

An example using the Hough circle detector

 1/**
 2 * @file houghcircles.cpp
 3 * @brief This program demonstrates circle finding with the Hough transform
 4 */
 5#include "opencv2/imgcodecs.hpp"
 6#include "opencv2/highgui.hpp"
 7#include "opencv2/imgproc.hpp"
 8
 9using namespace cv;
10using namespace std;
11
12int main(int argc, char** argv)
13{
14    //![load]
15    const char* filename = argc >=2 ? argv[1] : "smarties.png";
16
17    // Loads an image
18    Mat src = imread( samples::findFile( filename ), IMREAD_COLOR );
19
20    // Check if image is loaded fine
21    if(src.empty()){
22        printf(" Error opening image\n");
23        printf(" Program Arguments: [image_name -- default %s] \n", filename);
24        return EXIT_FAILURE;
25    }
26    //![load]
27
28    //![convert_to_gray]
29    Mat gray;
30    cvtColor(src, gray, COLOR_BGR2GRAY);
31    //![convert_to_gray]
32
33    //![reduce_noise]
34    medianBlur(gray, gray, 5);
35    //![reduce_noise]
36
37    //![houghcircles]
38    vector<Vec3f> circles;
39    HoughCircles(gray, circles, HOUGH_GRADIENT, 1,
40                 gray.rows/16,  // change this value to detect circles with different distances to each other
41                 100, 30, 1, 30 // change the last two parameters
42            // (min_radius & max_radius) to detect larger circles
43    );
44    //![houghcircles]
45
46    //![draw]
47    for( size_t i = 0; i < circles.size(); i++ )
48    {
49        Vec3i c = circles[i];
50        Point center = Point(c[0], c[1]);
51        // circle center
52        circle( src, center, 1, Scalar(0,100,100), 3, LINE_AA);
53        // circle outline
54        int radius = c[2];
55        circle( src, center, radius, Scalar(255,0,255), 3, LINE_AA);
56    }
57    //![draw]
58
59    //![display]
60    imshow("detected circles", src);
61    waitKey();
62    //![display]
63
64    return EXIT_SUCCESS;
65}