Guest User

Untitled

a guest
Apr 24th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. #include <opencv2/opencv.hpp>
  5. using namespace cv;
  6. #pragma comment(lib, "opencv_world340.lib")
  7.  
  8. int main(void)
  9. {
  10. Mat cat_img = imread("cat.png", CV_LOAD_IMAGE_GRAYSCALE);
  11.  
  12. threshold(cat_img, cat_img, 127, 255, THRESH_BINARY);
  13.  
  14. vector<vector<Point> > contours;
  15. vector<Vec4i> hierarchy;
  16.  
  17. findContours(cat_img, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
  18.  
  19. vector<vector<Point> > contours_poly(contours.size());
  20.  
  21. for (int i = 0; i < contours.size(); i++)
  22. approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);
  23.  
  24. Mat cat_contours = Mat::zeros(cat_img.size(), CV_8UC3);
  25.  
  26. for (int i = 0; i < contours_poly.size(); i++)
  27. {
  28. if(1 == contours_poly[i].size())
  29. {
  30. line(cat_contours, contours_poly[i][0], contours_poly[i][0], Scalar(0, 255, 0), 1, 8, 0);
  31. }
  32. else if (2 == contours_poly[i].size())
  33. {
  34. line(cat_contours, contours_poly[i][0], contours_poly[i][1], Scalar(0, 0, 255), 1, 8, 0);
  35. }
  36. else
  37. {
  38. for (int j = 0; j < contours_poly[i].size() - 1; j++)
  39. line(cat_contours, contours_poly[i][j], contours_poly[i][j + 1], Scalar(255, 0, 0), 1, 8, 0);
  40.  
  41. line(cat_contours, contours_poly[i][contours_poly[i].size() - 1], contours_poly[i][0], Scalar(255, 0, 0), 1, 8, 0);
  42. }
  43. }
  44.  
  45. imshow("cat img", cat_contours);
  46.  
  47. waitKey(0);
  48.  
  49. destroyAllWindows();
  50.  
  51. return 0;
  52. }
Add Comment
Please, Sign In to add comment