main.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "opencv2/highgui/highgui.hpp"
  2. #include "opencv2/imgproc/imgproc.hpp"
  3. #include "opencv2/imgcodecs.hpp"
  4. #include <iostream>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. using namespace cv;
  8. using namespace std;
  9. Mat src; Mat src_gray;
  10. int thresh = 100;
  11. int max_thresh = 255;
  12. RNG rng(12345);
  13. /// Function header
  14. void thresh_callback(int, void* );
  15. /** @function main */
  16. int main( int argc, char** argv )
  17. {
  18. /// Load source image and convert it to gray
  19. src = imread( "C:\\Users\\Sky\\Downloads\\1.jpg", IMREAD_COLOR );
  20. /// Convert image to gray and blur it
  21. cvtColor( src, src_gray, COLOR_BGR2GRAY );
  22. blur( src_gray, src_gray, Size(3,3) );
  23. /// Create Window
  24. char* source_window = "Source";
  25. namedWindow( source_window, WINDOW_AUTOSIZE );
  26. imshow( source_window, src );
  27. createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh, thresh_callback );
  28. thresh_callback( 0, 0 );
  29. waitKey(0);
  30. return(0);
  31. }
  32. /** @function thresh_callback */
  33. void thresh_callback(int, void* )
  34. {
  35. Mat canny_output;
  36. vector<vector<Point> > contours;
  37. vector<Vec4i> hierarchy;
  38. /// Detect edges using canny
  39. Canny( src_gray, canny_output, thresh, thresh*2, 3 );
  40. /// Find contours
  41. findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
  42. /// Draw contours
  43. Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
  44. for( int i = 0; i < contours.size(); i++ )
  45. {
  46. Scalar color = Scalar( rng.uniform(255, 255), rng.uniform(255,255), rng.uniform(255,255) );
  47. drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );
  48. }
  49. /// Show in a window
  50. namedWindow( "Contours", WINDOW_AUTOSIZE );
  51. imshow( "Contours", drawing );
  52. }