OpenCV provides and inbuilt function to detect circles in your image. The Hough transform is a technique which can be used to isolate features of a particular shape within an image. The implementation of the circle transform in OpenCV uses a tricky method called the Hough gradient method ( Link to Google Books ).
cvHoughCircles( ) is the function provided in OpenCV.
double param1 = 100,
double param2 = 300,
int min_radius = 0,
int max_radius = 0
Following is a example code snippet.
// Allocating memory dynamically to store the circle regions detected
CvMemStorage* storage_var = cvCreateMemStorage(0);
// A sequence of circles will get stored in the results variable
CvSeq* results = cvHoughCircles(img, storage_var , CV_HOUGH_GRADIENT , 2 , img->height/3 );
// Using a for loop to access individual circles; draw a circle in the input image
for( int i = 0; i < results->total; i++ )
float* p = (float*) cvGetSeqElem( results, i );
CvPoint pt = cvPoint( cvRound( p ), cvRound( p ));
cvCircle(img,pt,cvRound( p ),cvScalar(0,0,255),1.8);
Some things to note before using cvHoughTransform( )
- The image used should be in grey-scale.
- Reduce noise in the image as much as possible. You can use cvSmooth( ) function with CV_GRADIENT or CV_MEDIAN types to achieve this. Also many other filters could be used depending on the image.
cvHoughCircles( ) is a very inefficient method! I had tried using it to detect the pupil in the eyes. It was a very lame try because pupil detection actually turned out to be a very complex procedure! I would like to share some of the experiments i tried by implementing hough transform.
Initially i converted image to grey scale and applied gaussian smooth. Implemeted cvHoughCircles( ) on this image. You can see that the circle detection has been all over the place. Even the pupil which i wanted to detect is not accurate! So basically i had to filter more and reduce features in the image.
So next i just increased the intensity levels of the pixels. I can say that's one method which worked for me in this case. The number of circles detected was reduced and also a more accurate pupil boundary was detected. Similarly you can try various other filters.