In this blog we are going to learn how to write c++ program to detect circle in image using opencv computer vision library. We will learn how to use Hough Transform to find circles in an image.

detect circle in image using opencv

To detect circle in image we need to follow below simple steps:

  1. Load image using opencv api imread(..) and convert it to gray-scale using cvtColor( src, gray, CV_BGR2GRAY );.
  2. Blur the image by GaussianBlur opencv api.
  3. Apply the Hough Transform to find the circles.
  4. Draw the circles detected.
  5. Show the result in opencv window.

c++ program to detect circle in image using opencv

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
 
using namespace cv;
using namespace std;
 
int main()
{
  Mat src, gray;
  src = imread( "sample.jpg", 1 );resize(src,src,Size(640,480));
  cvtColor( src, gray, CV_BGR2GRAY );
 
  GaussianBlur( gray, gray, Size(9, 9), 2, 2 );
 
  vector<Vec3f> circles;
 
  HoughCircles( gray, circles, CV_HOUGH_GRADIENT, 1, 50, 100, 30, 0, 0 );
 
  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( src, center, 3, Scalar(0,255,0), -1, 8, 0 );// circle center     
      circle( src, center, radius, Scalar(0,0,255), 3, 8, 0 );// circle outline
      cout << "center : " << center << "\nradius : " << radius << endl;
   }
 
  namedWindow( "Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE );
  imshow( "Hough Circle Transform Demo", src );
 
  waitKey(0);
  return 0;
}
HoughCircles( gray, circles, CV_HOUGH_GRADIENT, 1, 50, 100, 30, 0, 0 );

The opencv HoughCircles api require some adjustment of its parameters. Some time the parameters are required to customize based on the source image.

Ref:

http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_circle/hough_circle.html



Related Contents to follow