findContours_demo.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * @function findContours_Demo.cpp
  3. * @brief Demo code to find contours in an image
  4. * @author OpenCV team
  5. */
  6. #include "opencv2/imgcodecs.hpp"
  7. #include "opencv2/highgui.hpp"
  8. #include "opencv2/imgproc.hpp"
  9. #include <iostream>
  10. using namespace cv;
  11. using namespace std;
  12. Mat src_gray;
  13. int thresh = 100;
  14. RNG rng(12345);
  15. /// Function header
  16. void thresh_callback(int, void* );
  17. /**
  18. * @function main
  19. */
  20. int main( int argc, char** argv )
  21. {
  22. /// Load source image
  23. CommandLineParser parser( argc, argv, "{@input | HappyFish.jpg | input image}" );
  24. Mat src = imread( samples::findFile( parser.get<String>( "@input" ) ) );
  25. if( src.empty() )
  26. {
  27. cout << "Could not open or find the image!\n" << endl;
  28. cout << "Usage: " << argv[0] << " <Input image>" << endl;
  29. return -1;
  30. }
  31. /// Convert image to gray and blur it
  32. cvtColor( src, src_gray, COLOR_BGR2GRAY );
  33. blur( src_gray, src_gray, Size(3,3) );
  34. /// Create Window
  35. const char* source_window = "Source";
  36. namedWindow( source_window );
  37. imshow( source_window, src );
  38. const int max_thresh = 255;
  39. createTrackbar( "Canny thresh:", source_window, &thresh, max_thresh, thresh_callback );
  40. thresh_callback( 0, 0 );
  41. waitKey();
  42. return 0;
  43. }
  44. /**
  45. * @function thresh_callback
  46. */
  47. void thresh_callback(int, void* )
  48. {
  49. /// Detect edges using Canny
  50. Mat canny_output;
  51. Canny( src_gray, canny_output, thresh, thresh*2 );
  52. /// Find contours
  53. vector<vector<Point> > contours;
  54. vector<Vec4i> hierarchy;
  55. findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE );
  56. /// Draw contours
  57. Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
  58. for( size_t i = 0; i< contours.size(); i++ )
  59. {
  60. Scalar color = Scalar( rng.uniform(0, 256), rng.uniform(0,256), rng.uniform(0,256) );
  61. drawContours( drawing, contours, (int)i, color, 2, LINE_8, hierarchy, 0 );
  62. }
  63. /// Show in a window
  64. imshow( "Contours", drawing );
  65. }