以下代码实现了几个简单的图像处理,主要包括:平滑(Smooth)、开操作(Open)、闭操作(Close)、膨胀(dilate)、腐蚀(Erode)、图像梯度(Gradient)、顶帽(TopHat)、黑帽(BlackHat)等。程序代码如下:
1 #include <cv.h>
2 #include <highgui.h>
3
4 #pragma comment(lib,"cv.lib");
5 #pragma comment(lib,"highgui.lib");
6
7 int main(int argc,char**argv)
8 {
9 IplImage*src=NULL;
10 IplImage*dst=NULL;
11 cvNamedWindow("Source Process",CV_WINDOW_AUTOSIZE);
12 cvNamedWindow("Processing Image",CV_WINDOW_AUTOSIZE);
13 IplConvKernel*kernel=cvCreateStructuringElementEx(6,6,2,3,CV_SHAPE_ELLIPSE);
14
15 src=argc<=2?cvLoadImage("lena.jpg"):cvLoadImage(argv[1]);
16 dst=cvCreateImage(cvGetSize(src),IPL_DEPTH_8U,src->nChannels);
17
18 cvShowImage("Source Process",src);
19 //cvSmooth(src,dst,CV_GAUSSIAN); //Smooth operation(include:CV_BLUR CV_BLUR_NO_SCALE CV_MEDIAN CV_GAUSSIAN CV_BILATERAL)
20 //cvErode(src,dst); //Erode operation
21 cvDilate(src,dst); //Dilate operation
22 //cvMorphologyEx(src,dst,NULL,kernel,CV_MOP_TOPHAT); //Other image operations(include:CV_COM_OPEN CV_MOP_CLOSE CV_MOP_GRADIENT CV_MOP_TOPHAT CV_MOP_BLACKHAT)
23 cvShowImage("Processing Image",dst);
24 cvSaveImage("CV_DILATE.jpg",dst);
25
26 while(1)
27 if(cvWaitKey(100)==27)
28 break;
29
30 cvDestroyWindow("Processing Image");
31 cvDestroyWindow("Source Image");
32 cvReleaseImage(&src);
33 cvReleaseImage(&dst);
34
35 return 0;
36 }
2 #include <highgui.h>
3
4 #pragma comment(lib,"cv.lib");
5 #pragma comment(lib,"highgui.lib");
6
7 int main(int argc,char**argv)
8 {
9 IplImage*src=NULL;
10 IplImage*dst=NULL;
11 cvNamedWindow("Source Process",CV_WINDOW_AUTOSIZE);
12 cvNamedWindow("Processing Image",CV_WINDOW_AUTOSIZE);
13 IplConvKernel*kernel=cvCreateStructuringElementEx(6,6,2,3,CV_SHAPE_ELLIPSE);
14
15 src=argc<=2?cvLoadImage("lena.jpg"):cvLoadImage(argv[1]);
16 dst=cvCreateImage(cvGetSize(src),IPL_DEPTH_8U,src->nChannels);
17
18 cvShowImage("Source Process",src);
19 //cvSmooth(src,dst,CV_GAUSSIAN); //Smooth operation(include:CV_BLUR CV_BLUR_NO_SCALE CV_MEDIAN CV_GAUSSIAN CV_BILATERAL)
20 //cvErode(src,dst); //Erode operation
21 cvDilate(src,dst); //Dilate operation
22 //cvMorphologyEx(src,dst,NULL,kernel,CV_MOP_TOPHAT); //Other image operations(include:CV_COM_OPEN CV_MOP_CLOSE CV_MOP_GRADIENT CV_MOP_TOPHAT CV_MOP_BLACKHAT)
23 cvShowImage("Processing Image",dst);
24 cvSaveImage("CV_DILATE.jpg",dst);
25
26 while(1)
27 if(cvWaitKey(100)==27)
28 break;
29
30 cvDestroyWindow("Processing Image");
31 cvDestroyWindow("Source Image");
32 cvReleaseImage(&src);
33 cvReleaseImage(&dst);
34
35 return 0;
36 }
其中:
可以将Erode看做图像与Kernel的减操作,而Dilate看做加操作,且:
Open(src)=Erode(src)+Dilate(src)
Close(src)=Dilate(src)+Erode(src)
Gradient(src)=Dilate(src)-Erode(src)
TopHat(src)=src-open(src)
BlackHat(src)=close(src)-src
以Open操作为例,当迭代次数iteration为2时,表示:Erode(src)+Erode(src)+Dilate(src)+Dilate(src),而非:Erode(src)+Dilate(src)+Erode(src)+Dilate(src).