CannyDetector_Demo.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * @file CannyDetector_Demo.cpp
  3. * @brief Sample code showing how to detect edges using the Canny Detector
  4. * @author OpenCV team
  5. */
  6. #include "opencv2/imgproc.hpp"
  7. #include "opencv2/highgui.hpp"
  8. #include <iostream>
  9. using namespace cv;
  10. //![variables]
  11. Mat src, src_gray;
  12. Mat dst, detected_edges;
  13. int lowThreshold = 0;
  14. const int max_lowThreshold = 100;
  15. const int ratio = 3;
  16. const int kernel_size = 3;
  17. const char* window_name = "Edge Map";
  18. //![variables]
  19. /**
  20. * @function CannyThreshold
  21. * @brief Trackbar callback - Canny thresholds input with a ratio 1:3
  22. */
  23. static void CannyThreshold(int, void*)
  24. {
  25. //![reduce_noise]
  26. /// Reduce noise with a kernel 3x3
  27. blur( src_gray, detected_edges, Size(3,3) );
  28. //![reduce_noise]
  29. //![canny]
  30. /// Canny detector
  31. Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );
  32. //![canny]
  33. /// Using Canny's output as a mask, we display our result
  34. //![fill]
  35. dst = Scalar::all(0);
  36. //![fill]
  37. //![copyto]
  38. src.copyTo( dst, detected_edges);
  39. //![copyto]
  40. //![display]
  41. imshow( window_name, dst );
  42. //![display]
  43. }
  44. /**
  45. * @function main
  46. */
  47. int main( int argc, char** argv )
  48. {
  49. //![load]
  50. CommandLineParser parser( argc, argv, "{@input | fruits.jpg | input image}" );
  51. src = imread( samples::findFile( parser.get<String>( "@input" ) ), IMREAD_COLOR ); // Load an image
  52. if( src.empty() )
  53. {
  54. std::cout << "Could not open or find the image!\n" << std::endl;
  55. std::cout << "Usage: " << argv[0] << " <Input image>" << std::endl;
  56. return -1;
  57. }
  58. //![load]
  59. //![create_mat]
  60. /// Create a matrix of the same type and size as src (for dst)
  61. dst.create( src.size(), src.type() );
  62. //![create_mat]
  63. //![convert_to_gray]
  64. cvtColor( src, src_gray, COLOR_BGR2GRAY );
  65. //![convert_to_gray]
  66. //![create_window]
  67. namedWindow( window_name, WINDOW_AUTOSIZE );
  68. //![create_window]
  69. //![create_trackbar]
  70. /// Create a Trackbar for user to enter threshold
  71. createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
  72. //![create_trackbar]
  73. /// Show the image
  74. CannyThreshold(0, 0);
  75. /// Wait until user exit program by pressing a key
  76. waitKey(0);
  77. return 0;
  78. }