example.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "opencv2/highgui/highgui.hpp"
  2. #include "opencv2/imgproc/imgproc.hpp"
  3. #include <iostream>
  4. #include <cstdlib>
  5. using namespace cv;
  6. using namespace std;
  7. int main(int argc, char** argv) {
  8. string image_path; // image path for input image
  9. if(argc < 2)
  10. image_path = "sample.jpg";
  11. else
  12. image_path = argv[1];
  13. // declare images
  14. Mat src, gray, blur_image, threshold_output;
  15. // take input image
  16. src = imread(image_path, 1);
  17. // convert to grayscale
  18. cvtColor(src, gray, COLOR_BGR2GRAY);
  19. // add blurring to the input image
  20. blur(gray, blur_image, Size(3, 3));
  21. // binary threshold the input image
  22. threshold(gray, threshold_output, 200, 255, THRESH_BINARY);
  23. // show source image
  24. namedWindow("Source", WINDOW_AUTOSIZE);
  25. imshow("Source", src);
  26. // Convex Hull implementation
  27. Mat src_copy = src.clone();
  28. // contours vector
  29. vector< vector<Point> > contours;
  30. vector<Vec4i> hierarchy;
  31. // find contours for the thresholded image
  32. findContours(threshold_output, contours, hierarchy, RETR_TREE,
  33. CHAIN_APPROX_SIMPLE, Point(0, 0));
  34. // create convex hull vector
  35. vector< vector<Point> > hull(contours.size());
  36. // find convex hull for each contour
  37. for(int i = 0; i < contours.size(); i++)
  38. convexHull(Mat(contours[i]), hull[i], false);
  39. // create empty black image
  40. Mat drawing = Mat::zeros(threshold_output.size(), CV_8UC3);
  41. // draw contours and convex hull on the empty black image
  42. for(int i = 0; i < contours.size(); i++) {
  43. Scalar color_contours = Scalar(0, 255, 0); // color for contours : blue
  44. Scalar color = Scalar(255, 255, 255); // color for convex hull : white
  45. // draw contours
  46. drawContours(drawing, contours, i, color_contours, 2, 8, vector<Vec4i>(), 0, Point());
  47. // draw convex hull
  48. drawContours(drawing, hull, i, color, 2, 8, vector<Vec4i>(), 0, Point());
  49. }
  50. namedWindow("Output", WINDOW_AUTOSIZE);
  51. imshow("Output", drawing);
  52. waitKey(0);
  53. return 0;
  54. }