samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp#

Advanced morphology Transformations sample code Sample screenshot
Check the corresponding tutorial for more details

 1/**
 2 * @file Morphology_2.cpp
 3 * @brief Advanced morphology Transformations sample code
 4 * @author OpenCV team
 5 */
 6
 7#include "opencv2/imgproc.hpp"
 8#include "opencv2/imgcodecs.hpp"
 9#include "opencv2/highgui.hpp"
10#include <iostream>
11
12using namespace cv;
13
14/// Global variables
15Mat src, dst;
16
17int morph_elem = 0;
18int morph_size = 0;
19int morph_operator = 0;
20int const max_operator = 4;
21int const max_elem = 3;
22int const max_kernel_size = 21;
23
24const char* window_name = "Morphology Transformations Demo";
25
26
27/** Function Headers */
28void Morphology_Operations( int, void* );
29
30/**
31 * @function main
32 */
33int main( int argc, char** argv )
34{
35  //![load]
36  CommandLineParser parser( argc, argv, "{@input | baboon.jpg | input image}" );
37  src = imread( samples::findFile( parser.get<String>( "@input" ) ), IMREAD_COLOR );
38  if (src.empty())
39  {
40    std::cout << "Could not open or find the image!\n" << std::endl;
41    std::cout << "Usage: " << argv[0] << " <Input image>" << std::endl;
42    return EXIT_FAILURE;
43  }
44  //![load]
45
46  //![window]
47  namedWindow( window_name, WINDOW_AUTOSIZE ); // Create window
48  //![window]
49
50  //![create_trackbar1]
51  /// Create Trackbar to select Morphology operation
52  createTrackbar("Operator:\n 0: Opening - 1: Closing  \n 2: Gradient - 3: Top Hat \n 4: Black Hat", window_name, &morph_operator, max_operator, Morphology_Operations );
53  //![create_trackbar1]
54
55  //![create_trackbar2]
56  /// Create Trackbar to select kernel type
57  createTrackbar( "Element:\n 0: Rect - 1: Cross - 2: Ellipse - 3: Diamond", window_name,
58                  &morph_elem, max_elem,
59                  Morphology_Operations );
60  //![create_trackbar2]
61
62  //![create_trackbar3]
63  /// Create Trackbar to choose kernel size
64  createTrackbar( "Kernel size:\n 2n +1", window_name,
65                  &morph_size, max_kernel_size,
66                  Morphology_Operations );
67  //![create_trackbar3]
68
69  /// Default start
70  Morphology_Operations( 0, 0 );
71
72  waitKey(0);
73  return 0;
74}
75
76//![morphology_operations]
77/**
78 * @function Morphology_Operations
79 */
80void Morphology_Operations( int, void* )
81{
82  // Since MORPH_X : 2,3,4,5 and 6
83  //![operation]
84  int operation = morph_operator + 2;
85  //![operation]
86
87  Mat element = getStructuringElement( morph_elem, Size( 2*morph_size + 1, 2*morph_size+1 ), Point( morph_size, morph_size ) );
88
89  /// Apply the specified morphology operation
90  morphologyEx( src, dst, operation, element );
91  imshow( window_name, dst );
92}
93//![morphology_operations]