1 #include "opencv2/imgproc/imgproc.hpp" 2 #include "opencv2/highgui/highgui.hpp" 3 #include "highgui.h" 4 #include <stdlib.h> 5 #include <stdio.h> 6 7 using namespace cv; 8 9 /// 全局变量 10 Mat src, erosion_dst, dilation_dst; 11 12 int erosion_elem = 0; 13 int erosion_size = 0; 14 int dilation_elem = 0; 15 int dilation_size = 0; 16 int const max_elem = 2; 17 int const max_kernel_size = 21; 18 19 /** Function Headers */ 20 void Erosion( int, void* ); 21 void Dilation( int, void* ); 22 23 /** @function main */ 24 int main( int argc, char** argv ) 25 { 26 /// Load 图像 27 src = imread( argv[1] ); 28 29 if( !src.data ) 30 { return -1; } 31 32 /// 创建显示窗口 33 namedWindow( "Erosion Demo", CV_WINDOW_AUTOSIZE ); 34 namedWindow( "Dilation Demo", CV_WINDOW_AUTOSIZE ); 35 cvMoveWindow( "Dilation Demo", src.cols, 0 ); 36 37 /// 创建腐蚀 Trackbar 38 createTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Erosion Demo", 39 &erosion_elem, max_elem, 40 Erosion ); 41 42 createTrackbar( "Kernel size:\n 2n +1", "Erosion Demo", 43 &erosion_size, max_kernel_size, 44 Erosion ); 45 46 /// 创建膨胀 Trackbar 47 createTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Dilation Demo", 48 &dilation_elem, max_elem, 49 Dilation ); 50 51 createTrackbar( "Kernel size:\n 2n +1", "Dilation Demo", 52 &dilation_size, max_kernel_size, 53 Dilation ); 54 55 /// Default start 56 Erosion( 0, 0 ); 57 Dilation( 0, 0 ); 58 59 waitKey(0); 60 return 0; 61 } 62 63 /** @function Erosion */ 64 void Erosion( int, void* ) 65 { 66 int erosion_type; 67 if( erosion_elem == 0 ){ erosion_type = MORPH_RECT; } 68 else if( erosion_elem == 1 ){ erosion_type = MORPH_CROSS; } 69 else if( erosion_elem == 2) { erosion_type = MORPH_ELLIPSE; } 70 71 Mat element = getStructuringElement( erosion_type, 72 Size( 2*erosion_size + 1, 2*erosion_size+1 ), 73 Point( erosion_size, erosion_size ) ); 74 75 /// 腐蚀操作 76 erode( src, erosion_dst, element ); 77 imshow( "Erosion Demo", erosion_dst ); 78 } 79 80 /** @function Dilation */ 81 void Dilation( int, void* ) 82 { 83 int dilation_type; 84 if( dilation_elem == 0 ){ dilation_type = MORPH_RECT; } 85 else if( dilation_elem == 1 ){ dilation_type = MORPH_CROSS; } 86 else if( dilation_elem == 2) { dilation_type = MORPH_ELLIPSE; } 87 88 Mat element = getStructuringElement( dilation_type, 89 Size( 2*dilation_size + 1, 2*dilation_size+1 ), 90 Point( dilation_size, dilation_size ) ); 91 ///膨胀操作 92 dilate( src, dilation_dst, element ); 93 imshow( "Dilation Demo", dilation_dst ); 94 }