OpenCV案例(二):选取圆对象

     OpenCV提供了一些基本的形态学处理方法与绘图操作,比如膨胀、腐蚀、开闭操作、画圆,画椭圆,画线,画矩形,在图像里插入文字等功能。

代码:

 
  1. #include <iostream>

  2. #include <opencv2/core/core.hpp>

  3. #include <opencv2/highgui/highgui.hpp>

  4. #include <opencv2/imgproc/imgproc.hpp>

  5. #include <opencv2/opencv.hpp>

  6. #include <math.h>

  7. #include <iostream>

  8.  
  9. using namespace std;

  10. using namespace cv;

  11.  
  12. //double threshold = 200.0;

  13. Mat BinaryImg,morhImage;

  14.  
  15. int main()

  16. {

  17.  
  18. Mat img = imread("../img/33.png", IMREAD_GRAYSCALE);

  19. imshow("原图", img);

  20.  
  21. threshold(img , BinaryImg ,0 ,255,THRESH_BINARY |THRESH_OTSU);

  22. imshow("二值化",BinaryImg);

  23.  
  24. //形态学处理

  25. Mat kernel = getStructuringElement(MORPH_RECT, Size(4, 4));

  26. morphologyEx(BinaryImg, morhImage, MORPH_OPEN, kernel); //去掉杂点

  27. imshow("形态学结果", morhImage);

  28.  
  29. vector<vector<Point>> contours;

  30. Mat resutimg = Mat::zeros(img.size(),CV_8UC3);

  31. findContours(morhImage, contours, RETR_TREE, CHAIN_APPROX_SIMPLE); //找到图像轮廓

  32. for (int i = 0; i < contours.size(); i++)

  33. {

  34. double area = contourArea(contours[i]); //去掉小区域

  35. if(area < 100 ) continue;

  36. Rect rect = boundingRect(contours[i]); //根据外轮廓长宽比率寻找圆

  37. float ratio = (float)(rect.width) / rect.height;

  38. if (ratio > 0.9 && ratio < 1.1)

  39. {

  40. drawContours(resutimg, contours, i, Scalar(0, 0, 250),-1); //找到圆的轮廓,-1代表填充

  41.  
  42. int x = rect.x + rect.width / 2;

  43. int y = rect.y + rect.height / 2;

  44. //circle(resutimg, Point(x, y), 2, Scalar(0, 0, 250),2); //画小圆点

  45. cout << "circle area : " << area << endl;

  46. cout << "circle length : " << arcLength(contours[i], true);

  47. cout << "circle center : x= " << x<<" , y = "<< y << endl;

  48. }

  49. }

  50.  
  51. imshow("result", resutimg); //绘制圆的轮廓与圆心

  52. waitKey(0);

  53. }

结果:

OpenCV案例(二):选取圆对象

OpenCV案例(二):选取圆对象

OpenCV案例(二):选取圆对象

OpenCV案例(二):选取圆对象

https://blog.csdn.net/tuwenqi2013/article/details/83692447