Sunday, 13 April 2014

Project 2.0. Detecting Circles from a Video Input

I hope you are familiar with Hough Transform.
In this post, I will show you how to detect circle from a video input using Hough Transform.

We know how to detect circles (from previous post), and if have gone through my previous tutorials, you would have a basic idea of how video, in form of frames, is inputted from the webcam and is outputted to the window.

Let's combine these two concepts and build a simple application.

#include<iostream>
#include<highgui.h>
#include<cv.h>
using namespace std;
using namespace cv;

int main()
{
 VideoCapture cap(0);
 Mat frame; // to capture from the webcam
 Mat img; // to process the 'frame'
 namedWindow("video"); //video output
 namedWindow("shapes"); //grayscale output
 vector<Vec3f> circles; //vector to store data from Hough Transfrom

 while(char(waitKey(1))!='q'){

  cap>>frame;
  //convert frame to grayscale
  cvtColor(frame,img,CV_RGB2GRAY);
  imshow("shapes",img);

  //apply HT to grayscale image 'img'
  HoughCircles(img,circles,CV_HOUGH_GRADIENT,1,10,100,50,5);
  // Here you can vary the second last argument(i.e. 50), according
  //to the threshold of your video.

  for(int i=0;i<circles.size();i++){

  //get 'center' and 'radius' of the detected circles
   Point center(cvRound(circles[i][0]),cvRound(circles[i][1]));
   int radius=cvRound(circles[i][2]);

   //draw center of the detected circle
   circle(frame,center,3,Scalar(0,0,255),-1);

   //draw the outline of circle
   circle(frame,center,radius,Scalar(0,0,255),3,8,0);
   }
  imshow("video",frame);
 }
 return 0;
}


Result:

This would seem to be easy, if you are thorough with most of my previous posts.

Everything until now was a child's play.
Real OpenCV begins from now.
Now, we will be focusing on algorithms and applying it in real life problems.



No comments:

Post a Comment