Thursday, October 20, 2011

OpenCV: Fun with filters and convolution (code)

To view the post click OpenCV: Fun with filters and convolution
#include "cv.h"
#include "highgui.h"
#include "stdio.h"


int main(int argc, char** argv)
{
IplImage* img = cvLoadImage("dad_mom.jpg",0);
IplImage* dst;
IplImage* dst1;
IplImage* dst2;
IplImage* dst3;
IplImage* dst4;
int i,j,k;
int height,width,step,channels;
uchar* data;
uchar* data1;
uchar* outdata;
CvScalar s;
CvScalar lodiff,highdiff,newval;

// get the image data
height = img->height;
width = img->width;
step = img->widthStep;
channels = img->nChannels;
data = (uchar *)img->imageData;



double a[9]={-1,20,1,-1,20,1,-1,20,1};



//double a[9]={1/16,1/8,1/16,1/8,1/4,1/8,1/16,1/8,1/16};
double values[9]={1/16,0,-1/16,2/16,0,-2/16,1/16,0,-1/16};

CvPoint seed;
CvMat kernel= cvMat(3,3,CV_32FC1,a);
printf("Processing a %d x %d image with %d channels\n",height,width,channels);

// Create windows

cvNamedWindow("Original",CV_WINDOW_AUTOSIZE);
cvNamedWindow("Flood Fill",CV_WINDOW_AUTOSIZE);
cvNamedWindow("Smooth",CV_WINDOW_AUTOSIZE);
cvNamedWindow("Erode",CV_WINDOW_AUTOSIZE);
cvNamedWindow("Dilate",CV_WINDOW_AUTOSIZE);
cvNamedWindow("Filter",CV_WINDOW_AUTOSIZE);
cvNamedWindow("Smooth1",CV_WINDOW_AUTOSIZE);

// Original image
cvShowImage("Original", img);

/* Flood fill in white patches intensity > 170.0 */

highdiff=cvRealScalar(5.0);
lodiff=cvRealScalar(5.0);
newval=cvRealScalar(150.0);

for(i=0;i 170.0)
{
seed=cvPoint(j,i);
//printf("data=%dFlood
seed=%d,%d\n",data[i*step+j*channels+k],i,j);


cvFloodFill(img,seed,newval,lodiff,highdiff,
NULL,CV_FLOODFILL_FIXED_RANGE,NULL);

}
else
{
;
}
}
}
//printf("\n");
}

cvShowImage("Flood Fill",img);

// Gaussian smooth

dst = cvCloneImage(img);
cvSmooth( img, dst, CV_GAUSSIAN, 3, 3, 0, 0 );
cvShowImage("Smooth",dst);

// Erode the image
dst1 = cvCloneImage(img);
IplConvKernel* kern = cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_RECT,values);
cvErode(dst,dst1,kern,1);
cvShowImage("Erode",dst1);

// Perform dilation operation
dst2 = cvCloneImage(img);
cvDilate(dst1,dst2,kern,1);
cvShowImage("Dilate",dst2);


// Filter the image with convolution kernel. Sharpen the image
dst3 = cvCloneImage(img);
printf("reached here\n");
cvFilter2D(dst2,dst3,&kernel,cvPoint(-1,-1));
cvShowImage("Filter",dst3);

// Smoothen the image

dst4 = cvCloneImage(img);
cvSmooth( dst3, dst4, CV_MEDIAN, 3, 0, 0, 0 );
cvShowImage("Smooth1",dst4);

// Cleanup
cvWaitKey(0);
cvReleaseImage(&img);
cvReleaseImage(&dst);
cvDestroyWindow("Original");
cvDestroyWindow("Restore");
}




No comments:

Post a Comment