thinning.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include <iostream>
  2. #include "opencv2/imgproc.hpp"
  3. #include "opencv2/highgui.hpp"
  4. #include "opencv2/ximgproc.hpp"
  5. using namespace std;
  6. using namespace cv;
  7. int main()
  8. {
  9. Mat img = imread("opencv-logo.png", IMREAD_COLOR);
  10. resize(img, img, Size(), 0.5, 0.5, INTER_LINEAR_EXACT);
  11. /// Threshold the input image
  12. Mat img_grayscale, img_binary;
  13. cvtColor(img, img_grayscale,COLOR_BGR2GRAY);
  14. threshold(img_grayscale, img_binary, 0, 255, THRESH_OTSU | THRESH_BINARY_INV);
  15. /// Apply thinning to get a skeleton
  16. Mat img_thinning_ZS, img_thinning_GH;
  17. ximgproc::thinning(img_binary, img_thinning_ZS, ximgproc::THINNING_ZHANGSUEN);
  18. ximgproc::thinning(img_binary, img_thinning_GH, ximgproc::THINNING_GUOHALL);
  19. /// Make 3 channel images from thinning result
  20. Mat result_ZS(img.rows, img.cols, CV_8UC3), result_GH(img.rows, img.cols, CV_8UC3);
  21. Mat in[] = { img_thinning_ZS, img_thinning_ZS, img_thinning_ZS };
  22. Mat in2[] = { img_thinning_GH, img_thinning_GH, img_thinning_GH };
  23. int from_to[] = { 0,0, 1,1, 2,2 };
  24. mixChannels( in, 3, &result_ZS, 1, from_to, 3 );
  25. mixChannels( in2, 3, &result_GH, 1, from_to, 3 );
  26. /// Combine everything into a canvas
  27. Mat canvas(img.rows, img.cols * 3, CV_8UC3);
  28. img.copyTo( canvas( Rect(0, 0, img.cols, img.rows) ) );
  29. result_ZS.copyTo( canvas( Rect(img.cols, 0, img.cols, img.rows) ) );
  30. result_GH.copyTo( canvas( Rect(img.cols*2, 0, img.cols, img.rows) ) );
  31. /// Visualize result
  32. imshow("Skeleton", canvas); waitKey(0);
  33. return 0;
  34. }