Saturday, February 23, 2013

Contours in openCV

Detecting contours.


The process of detecting contours is one of the simples.

Load the image -> Change to gray --> use the threshold function --> find the contour --> draw the contours

The code

//Load the image in colour
        flag=(double) getTickCount();
        imagen=imread(argv[1],CV_LOAD_IMAGE_UNCHANGED);
        flagLoad=getTick(flag);
//Change the image to gray
        flag=(double)getTickCount();
        cvtColor(imagen,imgGris,CV_BGR2GRAY);
        flag2Gray=getTick(flag);
//use the threshold to separate few objects
        flag=(double)getTickCount();
        threshold(imgGris,imgContorno,122,255,THRESH_BINARY);
        flagThreshold=getTick(flag);
//we need a place to leave the new iamge
        flag=(double)getTickCount();
        Mat dst = Mat::zeros(imgGris.rows,imgGris.cols,CV_8UC3);
        flagCreate=getTick(flag);

        namedWindow("gris",CV_WINDOW_NORMAL);
        namedWindow("contorno",CV_WINDOW_NORMAL);
        namedWindow("binario",CV_WINDOW_NORMAL);

        imshow ("gris",imgGris);
        imshow ("contorno",imgContorno);
        cvMoveWindow("gris",300,50);
        cvMoveWindow("contorno",600,50);

vector< vector<Point> > vecContornos;
vector<Vec4i>jerarquia;
//Find the contours
        flag = (double)getTickCount();
        findContours(imgContorno,vecContornos,jerarquia,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);
        flagFind =getTick(flag);
        flag = (double)getTickCount();
        for (int idx=0;idx >=0;idx=jerarquia[idx][0])
        {
                drawContours(dst,vecContornos,idx,WHITE,5,8,jerarquia);
        }

The results 

And finally we have this results from the original image


Original image


Result image
 All the values are in milliseconds 

This exercise give us a useful information

The main information is the threshold to separate the right image (12 ms) and find the contours (31 ms) around 50 ms to detect objects, it's not really bad for a dive which could use this information.

But the structural analysis could be take more time, we will what happen in the next exercises 

Any comment will be appreciated

No comments:

Post a Comment