OpenCV  3.0.0-rc1
Open Source Computer Vision
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
Hough Circle Transform

Goal

In this tutorial you will learn how to:

Theory

Hough Circle Transform

Code

  1. What does this program do?
    • Loads an image and blur it to reduce the noise
    • Applies the Hough Circle Transform to the blurred image .
    • Display the detected circle in a window.
  2. The sample code that we will explain can be downloaded from here. A slightly fancier version (which shows trackbars for changing the threshold values) can be found here.
    1 #include "opencv2/imgcodecs.hpp"
    4 
    5 #include <iostream>
    6 
    7 using namespace cv;
    8 using namespace std;
    9 
    10 static void help()
    11 {
    12  cout << "\nThis program demonstrates circle finding with the Hough transform.\n"
    13  "Usage:\n"
    14  "./houghcircles <image_name>, Default is ../data/board.jpg\n" << endl;
    15 }
    16 
    17 int main(int argc, char** argv)
    18 {
    19  const char* filename = argc >= 2 ? argv[1] : "../data/board.jpg";
    20 
    21  Mat img = imread(filename, 0);
    22  if(img.empty())
    23  {
    24  help();
    25  cout << "can not open " << filename << endl;
    26  return -1;
    27  }
    28 
    29  Mat cimg;
    30  medianBlur(img, img, 5);
    31  cvtColor(img, cimg, COLOR_GRAY2BGR);
    32 
    33  vector<Vec3f> circles;
    34  HoughCircles(img, circles, HOUGH_GRADIENT, 1, 10,
    35  100, 30, 1, 30 // change the last two parameters
    36  // (min_radius & max_radius) to detect larger circles
    37  );
    38  for( size_t i = 0; i < circles.size(); i++ )
    39  {
    40  Vec3i c = circles[i];
    41  circle( cimg, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, LINE_AA);
    42  circle( cimg, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, LINE_AA);
    43  }
    44 
    45  imshow("detected circles", cimg);
    46  waitKey();
    47 
    48  return 0;
    49 }
    bool empty() const
    Returns true if the array has no elements.
    Scalar_< double > Scalar
    Definition: types.hpp:597
    void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0)
    Converts an image from one color space to another.
    Mat imread(const String &filename, int flags=IMREAD_COLOR)
    Loads an image from a file.
    void imshow(const String &winname, InputArray mat)
    Displays an image in the specified window.
    Definition: imgproc.hpp:513
    void medianBlur(InputArray src, OutputArray dst, int ksize)
    Blurs an image using the median filter.
    Template class for short numerical vectors, a partial case of Matx.
    Definition: matx.hpp:300
    void HoughCircles(InputArray image, OutputArray circles, int method, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0)
    Finds circles in a grayscale image using the Hough transform.
    antialiased line
    Definition: core.hpp:207
    for i
    Definition: modelConvert.m:63
    basically 21HT, described in
    Definition: imgproc.hpp:446
    int main(int argc, const char *argv[])
    Definition: facerec_demo.cpp:67
    n-dimensional dense array class
    Definition: mat.hpp:726
    void circle(InputOutputArray img, Point center, int radius, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
    Draws a circle.
    Point2i Point
    Definition: types.hpp:181
    int waitKey(int delay=0)
    Waits for a pressed key.

Explanation

  1. Load an image
    src = imread( argv[1], 1 );
    if( !src.data )
    { return -1; }
  2. Convert it to grayscale:
    cvtColor( src, src_gray, COLOR_BGR2GRAY );
  3. Apply a Gaussian blur to reduce noise and avoid false circle detection:
    GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 );
  4. Proceed to apply Hough Circle Transform:
    vector<Vec3f> circles;
    HoughCircles( src_gray, circles, HOUGH_GRADIENT, 1, src_gray.rows/8, 200, 100, 0, 0 );
    with the arguments:
    • src_gray: Input image (grayscale).
    • circles: A vector that stores sets of 3 values: \(x_{c}, y_{c}, r\) for each detected circle.
    • HOUGH_GRADIENT: Define the detection method. Currently this is the only one available in OpenCV.
    • dp = 1: The inverse ratio of resolution.
    • min_dist = src_gray.rows/8: Minimum distance between detected centers.
    • param_1 = 200: Upper threshold for the internal Canny edge detector.
    • param_2 = 100*: Threshold for center detection.
    • min_radius = 0: Minimum radio to be detected. If unknown, put zero as default.
    • max_radius = 0: Maximum radius to be detected. If unknown, put zero as default.
  5. Draw the detected circles:
    for( size_t i = 0; i < circles.size(); i++ )
    {
    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(0,0,255), 3, 8, 0 );
    }
    You can see that we will draw the circle(s) on red and the center(s) with a small green dot
  6. Display the detected circle(s):
    namedWindow( "Hough Circle Transform Demo", WINDOW_AUTOSIZE );
    imshow( "Hough Circle Transform Demo", src );
  7. Wait for the user to exit the program

Result

The result of running the code above with a test image is shown below:

Hough_Circle_Tutorial_Result.jpg