connected_components.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <opencv2/core/utility.hpp>
  2. #include "opencv2/imgproc.hpp"
  3. #include "opencv2/imgcodecs.hpp"
  4. #include "opencv2/highgui.hpp"
  5. #include <iostream>
  6. using namespace cv;
  7. using namespace std;
  8. Mat img;
  9. int threshval = 100;
  10. static void on_trackbar(int, void*)
  11. {
  12. Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);
  13. Mat labelImage(img.size(), CV_32S);
  14. int nLabels = connectedComponents(bw, labelImage, 8);
  15. std::vector<Vec3b> colors(nLabels);
  16. colors[0] = Vec3b(0, 0, 0);//background
  17. for(int label = 1; label < nLabels; ++label){
  18. colors[label] = Vec3b( (rand()&255), (rand()&255), (rand()&255) );
  19. }
  20. Mat dst(img.size(), CV_8UC3);
  21. for(int r = 0; r < dst.rows; ++r){
  22. for(int c = 0; c < dst.cols; ++c){
  23. int label = labelImage.at<int>(r, c);
  24. Vec3b &pixel = dst.at<Vec3b>(r, c);
  25. pixel = colors[label];
  26. }
  27. }
  28. imshow( "Connected Components", dst );
  29. }
  30. int main( int argc, const char** argv )
  31. {
  32. CommandLineParser parser(argc, argv, "{@image|stuff.jpg|image for converting to a grayscale}");
  33. parser.about("\nThis program demonstrates connected components and use of the trackbar\n");
  34. parser.printMessage();
  35. cout << "\nThe image is converted to grayscale and displayed, another image has a trackbar\n"
  36. "that controls thresholding and thereby the extracted contours which are drawn in color\n";
  37. String inputImage = parser.get<string>(0);
  38. img = imread(samples::findFile(inputImage), IMREAD_GRAYSCALE);
  39. if(img.empty())
  40. {
  41. cout << "Could not read input image file: " << inputImage << endl;
  42. return EXIT_FAILURE;
  43. }
  44. imshow( "Image", img );
  45. namedWindow( "Connected Components", WINDOW_AUTOSIZE);
  46. createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
  47. on_trackbar(threshval, 0);
  48. waitKey(0);
  49. return EXIT_SUCCESS;
  50. }