Main Menu

Menu

Monday 23 May 2011

Image Dilation & Erosion using OpenCV

In this example I am using the OpenCV libraries from the Visual Studio 2010 programming in C++.
In this application we will erode and dilate an image. The code is clear and commented.

#include "stdafx.h"

#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include "cxcore.h"
#include "highgui.h"

int _tmain(int argc, _TCHAR* argv[])
{
        int iterations=1;

       //initialise the 3 images
      
        IplImage* source_image = NULL;
        IplImage* dilated_image = NULL;
        IplImage* eroded_image = NULL;

        //create 3 windows and their names
        cvNamedWindow("Source Image", 1);
        cvNamedWindow("Dilated Image",1);
        cvNamedWindow("Eroded Image",1);

        //load original image
        //if the name of your project is pr1
        //put a JPEG image in the pr1/pr1 folder
        //that the vs2010 will create
        source_image = cvLoadImage("1.jpg",1);
        cvShowImage( "Source Image", source_image );

        //make a copy of the original image
        dilated_image=cvCloneImage( source_image );
        eroded_image=cvCloneImage( source_image );

        //dilate image
        cvDilate(source_image,dilated_image,NULL,iterations);

        //erode image
        cvErode(source_image,eroded_image,NULL,iterations);

        //Present the processed images
        cvShowImage( "Dilated Image", dilated_image );
        cvShowImage( "Eroded Image", eroded_image );

        //Waits for a pressed key (0 delay)
        cvWaitKey(0);

        //destroys the window with the given name
        cvDestroyWindow( "Source Image" );
        cvDestroyWindow( "Dilated Image" );
        cvDestroyWindow( "Eroded Image" );

        //Deallocates the image header and the image data
        cvReleaseImage( &source_image );
        cvReleaseImage( &dilated_image );
        cvReleaseImage( &eroded_image );

        return 0;
}

The output of the above code:



4 iterations applied
One iteration applied

No comments:

Post a Comment