飞道的博客

opencv利用多边形逼近原理识别多边形和圆

549人阅读  评论(0)

  
  1. #include <iostream>
  2. #include <opencv2/opencv.hpp>
  3. #define MATCHMETHOD TM_SQDIFF_NORMED//宏定义匹配模式
  4. using namespace cv;
  5. using namespace std;
  6. int main(int argc, char** argv)
  7. {
  8. Mat src = imread( "几何.jpg");
  9. Mat src_gray, binary;
  10. Mat Triangle = src.clone(), Rect = src.clone(), Circlar = src.clone(), Pentagon = src.clone();
  11. if (src.empty()) {
  12. printf( "Could not load image...");
  13. return -1;
  14. }
  15. cv::imshow( "Input Image", src);
  16. //二值化
  17. cvtColor(src, src_gray, COLOR_BGR2GRAY);
  18. threshold(src_gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
  19. binary = ~binary;
  20. cv::imshow( "binary", binary);
  21. //发现轮廓
  22. vector< vector<Point>> contours;
  23. vector<Point> point;
  24. vector<Vec4i> hireachy;
  25. findContours(binary, contours, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
  26. int a= 0;
  27. int b= 0;
  28. int c= 0;
  29. int d= 0;
  30. //绘制出所有轮廓
  31. for ( size_t t = 0; t < contours.size(); t++)
  32. {
  33. int epsilon = 0.01*arcLength(contours[t], true);
  34. approxPolyDP(contours[t], point, epsilon, true);
  35. if (point.size() == 3)
  36. {
  37. drawContours(Triangle, contours, t, Scalar( 0, 0, 0), 2, 8, Mat(), 0, Point()); //dst必须先初始化
  38. a++;
  39. }
  40. else if (point.size() == 4)
  41. {
  42. drawContours(Rect, contours, t, Scalar( 0, 0, 0), 2, 8, Mat(), 0, Point()); //dst必须先初始化
  43. b++;
  44. }
  45. else if (point.size() == 5)
  46. {
  47. drawContours(Pentagon, contours, t, Scalar( 0, 0, 0), 2, 8, Mat(), 0, Point()); //dst必须先初始化
  48. c++;
  49. }
  50. else if (point.size()>= 10)
  51. {
  52. drawContours(Circlar, contours, t, Scalar( 0, 0, 0), 2, 8, Mat(), 0, Point()); //dst必须先初始化
  53. d++;
  54. }
  55. }
  56. cout << "三角形数目" << a << endl;
  57. cout << "四边形数目" << b << endl;
  58. cout<< "五边形数目" << c<< endl;
  59. cout<< "圆形形数目" << d<< endl;
  60. imshow( "Triangle", Triangle);
  61. imshow( "Pentagon", Pentagon);
  62. imshow( "Rect", Rect);
  63. imshow( "Circlar", Circlar);
  64. waitKey( 0);
  65. return 0;
  66. }

 


转载:https://blog.csdn.net/weixin_45790559/article/details/104413139
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场