hull_demo.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * @function hull_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 and convert it to gray
  23. CommandLineParser parser( argc, argv, "{@input | stuff.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. findContours( canny_output, contours, RETR_TREE, CHAIN_APPROX_SIMPLE );
  55. /// Find the convex hull object for each contour
  56. vector<vector<Point> >hull( contours.size() );
  57. for( size_t i = 0; i < contours.size(); i++ )
  58. {
  59. convexHull( contours[i], hull[i] );
  60. }
  61. /// Draw contours + hull results
  62. Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
  63. for( size_t i = 0; i< contours.size(); i++ )
  64. {
  65. Scalar color = Scalar( rng.uniform(0, 256), rng.uniform(0,256), rng.uniform(0,256) );
  66. drawContours( drawing, contours, (int)i, color );
  67. drawContours( drawing, hull, (int)i, color );
  68. }
  69. /// Show in a window
  70. imshow( "Hull demo", drawing );
  71. }