Monday, 14 April 2014

#11d. Application: Detecting number of circles in an image

This is actually a redundant post.
There was a problem which I came through in one of the OpenCV Hackathons.
It asked to detect number of circles in the given image.
This is very easily done by Hough Transform.

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

int thresh=100; 

void on_trackbar(int, void *){
    Mat img_gray;
    cvtColor(img,img_gray,CV_RGB2GRAY);
    vector<Vec3f> circles;
    HoughCircles(img_gray,circles,CV_HOUGH_GRADIENT,1,10,100,thresh,5);
    Mat img_show=img.clone();

    //the following line has to be added to count the number of circles 
    cout<<"Number of circles: "<<circles.size()<<endl;

    for(int i=0;i<circles.size();i++){
        Point center(cvRound(circles[i][0]),cvRound(circles[i][1]));
        int radius=cvRound(circles[i][2]);

        circle(img_show,center,3,Scalar(0,0,255),-1);

        circle(img_show,center,radius,Scalar(0,0,255),3,8,0);

    }
    imshow("Shapes",img_show);

}
int main()
{
    img =imread("images/linescircles.jpg");
    namedWindow("Shapes");
    imshow("Shapes",img);
    createTrackbar("Acc. threshold","Shapes",&thresh,300,on_trackbar);
    on_trackbar(0,0);
    while(char(waitKey(0))!='q'){}
    return 0;
}

cout<<"Number of circles: "<<circles.size()<<endl; 
prints out the number of circles.

No comments:

Post a Comment