Segmenting image(The connected components & The findContours function)

Connected Components

  1. void ConnectedComponents(Mat img)
  2. {
  3.   // Use connected components to divide our possibles parts of images 
  4.   Mat labels;
  5.   int num_objects= connectedComponents(img, labels);
  6.   // Check the number of objects detected
  7.   if(num_objects < 2 ){
  8.     cout << "No objects detected" << endl;
  9.     return;
  10.   }else{
  11.     cout << "Number of objects detected: " << num_objects - 1 << endl;
  12.   }
  13.   // Create output image coloring the objects
  14.   Mat output= Mat::zeros(img.rows,img.cols, CV_8UC3);
  15.   RNG rng( 0xFFFFFFFF );
  16.   for(int i=1; i<num_objects; i++){
  17.     Mat mask= labels==i;
  18.     output.setTo(randomColor(rng), mask);
  19.   }
  20.   imshow("Result", output);
  21.   miw->addImage("Result", output);
  22. }
  23.  
  24. void ConnectedComponentsStats(Mat img)
  25. {
  26.   // Use connected components with stats
  27.   Mat labels, stats, centroids;
  28.   int num_objects= connectedComponentsWithStats(img, labels, stats, centroids);
  29.   // Check the number of objects detected
  30.   if(num_objects < 2 ){
  31.     cout << "No objects detected" << endl;
  32.     return;
  33.   }else{
  34.     cout << "Number of objects detected: " << num_objects - 1 << endl;
  35.   }
  36.   // Create output image coloring the objects and show area
  37.   Mat output= Mat::zeros(img.rows,img.cols, CV_8UC3);
  38.   RNG rng( 0xFFFFFFFF );
  39.   for(int i=1; i<num_objects; i++){
  40.     cout << "Object "<< i << " with pos: " << centroids.at<Point2d>(i) << " with area " << stats.at<int>(i, CC_STAT_AREA) << endl;
  41.     Mat mask= labels==i;
  42.     output.setTo(randomColor(rng), mask);
  43.     // draw text with area
  44.     stringstream ss;
  45.     ss << "area: " << stats.at<int>(i, CC_STAT_AREA);
  46.  
  47.     putText(output, 
  48.       ss.str(), 
  49.       centroids.at<Point2d>(i), 
  50.       FONT_HERSHEY_SIMPLEX, 
  51.       0.4, 
  52.       Scalar(255,255,255));
  53.   }
  54.   imshow("Result", output);
  55.   miw->addImage("Result", output);
  56. }

Find Contours Basic

  1. void FindContoursBasic(Mat img)
  2. {
  3.   vector<vector<Point> > contours;
  4.   findContours(img, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
  5.   Mat output= Mat::zeros(img.rows,img.cols, CV_8UC3);
  6.   // Check the number of objects detected
  7.   if(contours.size() == 0 ){
  8.     cout << "No objects detected" << endl;
  9.     return;
  10.   }else{
  11.     cout << "Number of objects detected: " << contours.size() << endl;
  12.   }
  13.   RNG rng( 0xFFFFFFFF );
  14.   for(int i=0; i<contours.size(); i++)
  15.     drawContours(output, contours, i, randomColor(rng));
  16.   imshow("Result", output);
  17.   miw->addImage("Result", output);
  18. }

Leave a Reply

Your email address will not be published. Required fields are marked *