Sunday, June 20, 2010

Open CV Tutorial - Basic operations for images ' Canny edge detection'

 In the last tutorial I have discussed how to setup workspace for different IDEs and basic tutorials about Opencv. Now let us make some more good programs. Lets us make a program for canny edge detection. Canny edge is one of the most widely used edge detection programs used along with other edge detection like Sobel. Read more about Canny algorithm here.

In OpenCV we get a very good implementation of Canny algorithm. The function cvCanny finds the edges on the input image image and marks them in the output image edges using the Canny algorithm. The smallest of threshold1 and threshold2 is used for edge linking, the largest - to find initial segments of strong edges.A brief intro of function is as:-

void cvCanny( const CvArr* image, CvArr* edges, double threshold1,
              double threshold2, int aperture_size=3 );

Explanation of function:-


Input image.


Image to store the edges found by the function.


The first threshold.


The second threshold.

aperture_size ( a bit complicated :( but try to grasp it or use default-3 in most cases)


In all cases except 1, aperture_size ×aperture_size separable kernel
    will be used to calculate
    the derivative. For aperture_size=1 3x1 or 1x3 kernel is
    used (Gaussian smoothing is not done).
    There is also special value CV_SCHARR (=-1) that
    corresponds to 3x3 Scharr filter that may
    give more accurate results than 3x3 Sobel. Scharr aperture is:
| -3 0  3|
|-10 0 10|
| -3 0  3|
for x-derivative or transposed for y-derivative.
Now we will write a sample program :-

#include "cv.h"
#include "highgui.h"
int main()
IplImage* newImg; // original image
IplImage* grayImg; // gray image for the conversion of the original image
IplImage* cannyImg; // gray image for the canny edge detection
//load original image
newImg = cvLoadImage("apple.bmp",1);
//create a single channel 1 byte image (i.e. gray-level image)
grayImg = cvCreateImage( cvSize(newImg->width, newImg->height), IPL_DEPTH_8U, 1 );
//convert original color image (3 channel rgb color image) to gray-level image
cvCvtColor( newImg, grayImg, CV_BGR2GRAY );
cannyImg = cvCreateImage(cvGetSize(newImg), IPL_DEPTH_8U, 1);
// canny edge detection
cvCanny(grayImg, cannyImg, 50, 150, 3);
cvNamedWindow("src", 1);
cvShowImage( "src", newImg );
cvShowImage( "canny", cannyImg );
cvDestroyWindow( "src" );
cvDestroyWindow( "canny" );
cvReleaseImage( &newImg );
cvReleaseImage( &grayImg );
cvReleaseImage( &cannyImg );
return 0;


Also Read :- 


  1. hi

    If one image contains two images in square boxes.

    do you know how can I split one image in two images ?

    is there any open-source code I can use ?


  2. Thanks for the help Ritesh!