You are here:Home » image processing » Image Proseesing - Extacting Shapes using OpenCV

Image Proseesing - Extacting Shapes using OpenCV

// This is a program to find SQUARE shape and Circle shape

#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include < math.h >
int main(int argc, char* argv[])
{



    IplImage* img=0;
    IplImage* gray=0;

    CvMemStorage* storage = cvCreateMemStorage(0);
    CvSeq*  contours;

    img=cvLoadImage("shape.jpg");

    if(img==NULL)
    {
        printf("Error in opening image\n");
        return -1;
    }


    cvNamedWindow("win1",1);
    cvNamedWindow("win2",1);

    gray = cvCreateImage( cvSize(img->width, img->height), IPL_DEPTH_8U, 1 );
    cvCvtColor(img,gray,CV_BGR2GRAY );

    uchar *data;
    data=(uchar* )img->imageData;

    uchar *data_gray;
    data_gray=(uchar* )gray->imageData;

    int  step_g=gray->widthStep;
    int  step=img->widthStep;
    int channels=img->nChannels;

   


     for(int i=0;iheight;i=i++)
     {
         for(int j=0;jwidth;j++)
         {
             
             
             /////////////exracting  white
             if( (data[i*step+j*channels+0]>200) && (data[i*step+j*channels+1]>200) && (data[i*step+j*channels+2]>220) )
                 data_gray[i*step_g+j] = 255;


            else
                data_gray[i*step_g+j] = 0;

         }
         
     }

   // find counters in the gray image - object detection
    cvFindContours( gray, storage, &contours, sizeof(CvContour),
                    CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE , cvPoint(0,0) );

   

    double area;
    double p;
    double metric_s,metric_c;

// loop through all counturs   
for( ; contours != 0; contours = contours->h_next )
    {
        area=fabs( cvContourArea(contours,CV_WHOLE_SEQ ) );
        p=fabs( cvArcLength( contours, CV_WHOLE_SEQ, -1) );

        // determine metric for circle
        metric_c=area*4*3.14/(p*p);
        metric_s=area*16/(p*p);

        if(metric_c > 0.75f && metric_s > 1.0f)
            printf(" circle \n");

        else if(metric_s > 0.9f && metric_c < 0.8f )
            printf(" square \n");

        else
            printf(" nothing ");


        printf("area = %lf perimeter=%lf metric_c=%lf metric_s=%lf\n",p,area,metric_c,metric_s);



    }


     cvShowImage("win1",img);
     cvShowImage("win2",gray);

     cvWaitKey(0);
   
    cvDestroyWindow("win1");
    cvDestroyWindow("win2");

    cvReleaseImage(&img);
    cvReleaseImage(&gray);
   
   
   
   
    //printf("Hello World!\n");
    return 0;
}

0 comments:

Post a Comment