connected_components.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <iostream>
  2. #include <opencv2/core/utility.hpp>
  3. #include "opencv2/imgproc.hpp"
  4. #include "opencv2/imgcodecs.hpp"
  5. #include "opencv2/highgui.hpp"
  6. #include "opencv2/cudaimgproc.hpp"
  7. using namespace cv;
  8. using namespace std;
  9. using namespace cv::cuda;
  10. void colorLabels(const Mat1i& labels, Mat3b& colors) {
  11. colors.create(labels.size());
  12. for (int r = 0; r < labels.rows; ++r) {
  13. int const* labels_row = labels.ptr<int>(r);
  14. Vec3b* colors_row = colors.ptr<Vec3b>(r);
  15. for (int c = 0; c < labels.cols; ++c) {
  16. colors_row[c] = Vec3b(labels_row[c] * 131 % 255, labels_row[c] * 241 % 255, labels_row[c] * 251 % 255);
  17. }
  18. }
  19. }
  20. int main(int argc, const char** argv)
  21. {
  22. CommandLineParser parser(argc, argv, "{@image|stuff.jpg|image for converting to a grayscale}");
  23. parser.about("This program finds connected components in a binary image and assign each of them a different color.\n"
  24. "The connected components labeling is performed in GPU.\n");
  25. parser.printMessage();
  26. String inputImage = parser.get<string>(0);
  27. Mat1b img = imread(samples::findFile(inputImage), IMREAD_GRAYSCALE);
  28. Mat1i labels;
  29. if (img.empty())
  30. {
  31. cout << "Could not read input image file: " << inputImage << endl;
  32. return EXIT_FAILURE;
  33. }
  34. GpuMat d_img, d_labels;
  35. d_img.upload(img);
  36. cuda::connectedComponents(d_img, d_labels, 8, CV_32S);
  37. d_labels.download(labels);
  38. Mat3b colors;
  39. colorLabels(labels, colors);
  40. imshow("Labels", colors);
  41. waitKey(0);
  42. return EXIT_SUCCESS;
  43. }