OpenCV--求取图像多轮廓质心,并于图像上绘制显示质心及其坐标

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuoyueljl/article/details/53588271

1、源代码


  
  
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <opencv2/core/core.hpp>
  4. #include <opencv/cv.hpp>
  5. #include <opencv2/highgui/highgui.hpp>
  6. using namespace cv;
  7. using namespace std;
  8. Mat src;
  9. Mat src_gray;
  10. int thresh = 30;
  11. int max_thresh = 255;
  12. int main()
  13. {
  14. src = imread( "C:\\Users\\Lijunliang\\Desktop\\opencvpic\\2\\22.png" ,CV_LOAD_IMAGE_COLOR ); //注意路径得换成自己的
  15. cvtColor( src, src_gray, CV_BGR2GRAY );//灰度化
  16. GaussianBlur( src, src, Size(3,3), 0.1, 0, BORDER_DEFAULT );
  17. blur( src_gray, src_gray, Size(3,3) ); //滤波
  18. namedWindow( "image", CV_WINDOW_AUTOSIZE );
  19. imshow( "image", src );
  20. moveWindow("image",20,20);
  21. //定义Canny边缘检测图像
  22. Mat canny_output;
  23. vector <vector<Point> > contours;
  24. vector <Vec4i> hierarchy;
  25. //利用canny算法检测边缘
  26. Canny( src_gray, canny_output, thresh, thresh*3, 3 );
  27. namedWindow( "canny", CV_WINDOW_AUTOSIZE );
  28. imshow( "canny", canny_output );
  29. moveWindow("canny",550,20);
  30. //查找轮廓
  31. findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
  32. //计算轮廓矩
  33. vector <Moments> mu(contours.size() );
  34. for( int i = 0; i < contours.size(); i++ )
  35. {
  36. mu[i] = moments( contours[i], false );
  37. }
  38. //计算轮廓的质心
  39. vector<Point2f> mc( contours.size() );
  40. for( int i = 0; i < contours.size(); i++ )
  41. {
  42. mc[i] = Point2d( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 );
  43. }
  44. //画轮廓及其质心并显示
  45. Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
  46. for( int i = 0; i< contours.size(); i++ )
  47. {
  48. Scalar color = Scalar( 255, 0, 0);
  49. drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );
  50. circle( drawing, mc[i], 5, Scalar( 0, 0, 255), -1, 8, 0 );
  51. rectangle(drawing, boundingRect(contours.at(i)), cvScalar(0,255,0));
  52. char tam[100];
  53. sprintf(tam, "(%0.0f,%0.0f)",mc[i].x,mc[i].y);
  54. putText(drawing, tam, Point(mc[i].x, mc[i].y), FONT_HERSHEY_SIMPLEX, 0.4, cvScalar(255,0,255),1);
  55. }
  56. namedWindow( "Contours", CV_WINDOW_AUTOSIZE );
  57. imshow( "Contours", drawing );
  58. moveWindow("Contours",1100,20);
  59. waitKey(0);
  60. src.release();
  61. src_gray.release();
  62. return 0;
  63. }


2、获取实验结果




转载自:https://blog.csdn.net/zhuoyueljl/article/details/53588271

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuoyueljl/article/details/53588271

猜你喜欢

转载自blog.csdn.net/baidu_38172402/article/details/82789086
今日推荐