1 /** 2 * @file Morphology_1.cpp 3 * @brief Erosion and Dilation sample code 4 * @author OpenCV team 5 */ 6 7 #include "opencv2/imgproc/imgproc.hpp" 8 #include "opencv2/imgcodecs.hpp" 9 #include "opencv2/highgui/highgui.hpp" 10 #include <stdlib.h> 11 #include <stdio.h> 12 13 using namespace cv; 14 15 /// Global variables 16 Mat src, erosion_dst, dilation_dst; 17 18 int erosion_elem = 0; 19 int erosion_size = 0; 20 int dilation_elem = 0; 21 int dilation_size = 0; 22 int const max_elem = 2; 23 int const max_kernel_size = 21; 24 25 /** Function Headers */ 26 void Erosion( int, void* ); 27 void Dilation( int, void* ); 28 29 /** 30 * @function main 31 */ 32 int main( int, char** argv ) 33 { 34 /// Load an image 35 src = imread( argv[1] ); 36 37 if( src.empty() ) 38 { return -1; } 39 40 /// Create windows 41 namedWindow( "Erosion Demo", WINDOW_AUTOSIZE ); 42 namedWindow( "Dilation Demo", WINDOW_AUTOSIZE ); 43 moveWindow( "Dilation Demo", src.cols, 0 ); 44 45 /// Create Erosion Trackbar 46 createTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Erosion Demo", 47 &erosion_elem, max_elem, 48 Erosion ); 49 50 createTrackbar( "Kernel size:\n 2n +1", "Erosion Demo", 51 &erosion_size, max_kernel_size, 52 Erosion ); 53 54 /// Create Dilation Trackbar 55 createTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Dilation Demo", 56 &dilation_elem, max_elem, 57 Dilation ); 58 59 createTrackbar( "Kernel size:\n 2n +1", "Dilation Demo", 60 &dilation_size, max_kernel_size, 61 Dilation ); 62 63 /// Default start 64 Erosion( 0, 0 ); 65 Dilation( 0, 0 ); 66 67 waitKey(0); 68 return 0; 69 } 70 71 /** 72 * @function Erosion 73 */ 74 void Erosion( int, void* ) 75 { 76 int erosion_type = 0; 77 if( erosion_elem == 0 ){ erosion_type = MORPH_RECT; } 78 else if( erosion_elem == 1 ){ erosion_type = MORPH_CROSS; } 79 else if( erosion_elem == 2) { erosion_type = MORPH_ELLIPSE; } 80 81 Mat element = getStructuringElement( erosion_type, 82 Size( 2*erosion_size + 1, 2*erosion_size+1 ), 83 Point( erosion_size, erosion_size ) ); 84 /// Apply the erosion operation 85 erode( src, erosion_dst, element ); 86 imshow( "Erosion Demo", erosion_dst ); 87 } 88 89 /** 90 * @function Dilation 91 */ 92 void Dilation( int, void* ) 93 { 94 int dilation_type = 0; 95 if( dilation_elem == 0 ){ dilation_type = MORPH_RECT; } 96 else if( dilation_elem == 1 ){ dilation_type = MORPH_CROSS; } 97 else if( dilation_elem == 2) { dilation_type = MORPH_ELLIPSE; } 98 99 Mat element = getStructuringElement( dilation_type, 100 Size( 2*dilation_size + 1, 2*dilation_size+1 ), 101 Point( dilation_size, dilation_size ) ); 102 /// Apply the dilation operation 103 dilate( src, dilation_dst, element ); 104 imshow( "Dilation Demo", dilation_dst ); 105 } 106