imgproc_drawContours.cpp 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #include "opencv2/imgproc.hpp"
  2. #include "opencv2/highgui.hpp"
  3. using namespace cv;
  4. using namespace std;
  5. int main( int argc, char** argv )
  6. {
  7. Mat src;
  8. // the first command-line parameter must be a filename of the binary
  9. // (black-n-white) image
  10. if( argc != 2 || !(src=imread(argv[1], 0)).data)
  11. return -1;
  12. Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
  13. src = src > 1;
  14. namedWindow( "Source", 1 );
  15. imshow( "Source", src );
  16. vector<vector<Point> > contours;
  17. vector<Vec4i> hierarchy;
  18. findContours( src, contours, hierarchy,
  19. RETR_CCOMP, CHAIN_APPROX_SIMPLE );
  20. // iterate through all the top-level contours,
  21. // draw each connected component with its own random color
  22. int idx = 0;
  23. for( ; idx >= 0; idx = hierarchy[idx][0] )
  24. {
  25. Scalar color( rand()&255, rand()&255, rand()&255 );
  26. drawContours( dst, contours, idx, color, FILLED, 8, hierarchy );
  27. }
  28. namedWindow( "Components", 1 );
  29. imshow( "Components", dst );
  30. waitKey(0);
  31. }