Monday, October 6, 2008

Convert a Color image to Gray using OpenCV

Hello All
This is the source code for converting a Colour Image to gray image. I had make use of OpenCV library for this purpose.

#include "stdafx.h"
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"

IplImage* convert_grayscale(IplImage *img)
{
IplImage *gray_image,*gray_img0;
gray_image=cvCloneImage(img);
//check image is it gray or not if nor convert it to the gray
if(img->nChannels!=1)
{
//convert original image to gray_scale image
gray_img0 = cvCreateImage(cvSize( gray_image->width,gray_image->height), 8, 1 );
cvCvtColor(gray_image, gray_img0, CV_RGB2GRAY);
gray_image = cvCloneImage( gray_img0 );
}
return gray_image;
}

int _tmain(int argc, _TCHAR* argv[])
{
IplImage *Img =cvLoadImage("c:/program files/opencv/samples/c/fruits.jpg"),*gray_image;
cvNamedWindow("Image",1);
gray_image=convert_grayscale(Img);
cvShowImage("Image",gray_image);
cvWaitKey();
cvReleaseImage(&Img);
cvDestroyWindow("Image");
return 0;
}

No comments: