September 15, 2011

Detection of Circles using OpenCV


    In the last post, I discussed how to install OpenCV on Windows and how to create and run a project. Now I will show some simple OpenCV programs.

First, consider the program below, used for detection of green circles in the video. It also prints the centers of green circles detected in each frame.

PROGRAM:

#include"highgui.h"
#include"cv.h"
void main()
{

cvNamedWindow( "Example2", CV_WINDOW_AUTOSIZE );
CvCapture* capture = cvCreateCameraCapture(0);
IplImage* frame;
while(1) {

frame = cvQueryFrame( capture );
if( !frame ) break;
IplImage* result1=cvCreateImage(cvGetSize(frame),8,1);
IplImage* result=cvCreateImage(cvGetSize(frame),8,3);
cvCvtColor(frame,result,CV_BGR2RGB);
for(int y=0;y<result->height;y++)
{
 uchar* ptr = (uchar*) (result->imageData + y * result->widthStep);
   for( int x=0; x<result->width; x++ )
   {
      if(ptr[3*x+1]<=155 && ptr[3*x]<=255 && ptr[3*x+2]<=255)
    {
  ptr[3*x] = 0;
  ptr[3*x+1] =0;
  ptr[3*x+2] = 0;
  }
  else
  {
  ptr[3*x] = 255;
  ptr[3*x+1] = 255;
  ptr[3*x+2] = 255;
 }
}
}
cvCvtColor(result,result1,CV_BGR2GRAY);
CvMemStorage* storage = cvCreateMemStorage(0);
cvSmooth(result1, result1, CV_GAUSSIAN, 5, 5 );
CvSeq* results = cvHoughCircles(
result1,
storage,
CV_HOUGH_GRADIENT,
2,
result1->width/10
);
for( int i = 0; i < results->total; i++ ) {
float* p = (float*) cvGetSeqElem( results, i );
CvPoint pt = cvPoint( cvRound( p[0] ), cvRound( p[1] ) );
printf("\t%d %d",pt.x,pt.y);
cvCircle(
result1,
pt,
cvRound( p[2] ),
CV_RGB(0xff,0xff,0xff)
);
}

cvShowImage( "Example2", frame );
cvShowImage( "result1", result1 );
char c = cvWaitKey(33);
if( c == 27 ) break;
}
cvReleaseCapture( &capture );
cvDestroyWindow( "Example2" );

}


     You can easily modify this program to detect circles of other colors, to find number of circles, etc.
In the next post,  I will show how to install OpenCV on Linux platform and how to create and run a project on it. I will also show the serial communication in OpenCV.

No comments: