center_of_multipe_blob.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "opencv2/highgui/highgui.hpp"
  2. #include "opencv2/imgproc/imgproc.hpp"
  3. #include <iostream>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. using namespace cv;
  7. using namespace std;
  8. RNG rng(12345);
  9. void find_moments( Mat src );
  10. int main(int argc, char** argv)
  11. {
  12. /// Load source image, convert it to gray
  13. Mat src, gray;
  14. src = imread(argv[1], 1 );
  15. cvtColor( src, gray, COLOR_BGR2GRAY );
  16. namedWindow( "Source", WINDOW_AUTOSIZE );
  17. imshow( "Source", src );
  18. // call function to find_moments
  19. find_moments( gray );
  20. waitKey(0);
  21. return(0);
  22. }
  23. void find_moments( Mat gray )
  24. {
  25. Mat canny_output;
  26. vector<vector<Point> > contours;
  27. vector<Vec4i> hierarchy;
  28. /// Detect edges using canny
  29. Canny( gray, canny_output, 50, 150, 3 );
  30. // Find contours
  31. findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
  32. /// Get the moments
  33. vector<Moments> mu(contours.size() );
  34. for( int i = 0; i < contours.size(); i++ )
  35. { mu[i] = moments( contours[i], false ); }
  36. /// Get the centroid of figures.
  37. vector<Point2f> mc( contours.size() );
  38. for( int i = 0; i < contours.size(); i++ )
  39. { mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
  40. /// Draw contours
  41. Mat drawing(canny_output.size(), CV_8UC3, Scalar(255,255,255));
  42. for( int i = 0; i< contours.size(); i++ )
  43. {
  44. Scalar color = Scalar(167,151,0);
  45. drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );
  46. circle( drawing, mc[i], 4, color, -1, 7, 0 );
  47. }
  48. /// Show the resultant image
  49. namedWindow( "Contours", WINDOW_AUTOSIZE );
  50. imshow( "Contours", drawing );
  51. waitKey(0);
  52. }