Morphology_2.cpp 2.4 KB

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