MeterRead.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "MeterRead.h"
  2. constexpr auto PI = 3.1415926;
  3. constexpr auto CV_AA = 16;
  4. Point circle_center;
  5. int circle_radius;
  6. double MeterRead::GetResult(cv::Mat sourceMat, bool IsShowWnd)
  7. {
  8. Mat mat;
  9. sourceMat.copyTo(mat);
  10. if (IsShowWnd) {
  11. //imshow("原图", mat);
  12. waitKey(1);
  13. }
  14. int matCols = 500;
  15. Size size(500, 420);
  16. resize(mat, mat, size, (float)matCols / mat.cols, (float)matCols / mat.cols);
  17. int width = mat.cols;
  18. int height = mat.rows;
  19. Mat grayMat;
  20. cvtColor(mat, grayMat, COLOR_BGR2GRAY); // 转换为灰度图
  21. Mat gaussMat;
  22. GaussianBlur(grayMat, gaussMat, Size(3, 3), 0, 0);
  23. if (IsShowWnd) {
  24. //imshow("高斯模糊图", gaussMat);
  25. waitKey(1);
  26. }
  27. Mat dst;
  28. threshold(gaussMat, dst,120, 255, THRESH_BINARY_INV);//二值化阈值处理
  29. Mat biMat;
  30. bilateralFilter(dst, biMat, 9, 50, 50);
  31. if (IsShowWnd) {
  32. //imshow("滤波去噪图", biMat);
  33. waitKey(1);
  34. }
  35. Mat cannyMat;
  36. Canny(biMat, cannyMat,50, 200,3);//边缘检测
  37. if (IsShowWnd) {
  38. //imshow("边缘检测", cannyMat);
  39. waitKey(1);
  40. }
  41. vector<cv::Vec4i> lines;
  42. double begin_angle = 0;
  43. double end_angle = 0;
  44. double det_angle = 0;
  45. HoughLinesP(cannyMat, lines, 1, CV_PI / 180, 95, 120, 26);
  46. for (int i = 0; i < lines.size(); ++i) {
  47. Vec4i line_ = lines[i];
  48. double k = ((double)line_[3] - line_[1]) / ((double)line_[2] - line_[0]); //直线的斜率
  49. double angle = (atan(k) * 180 / PI); //直线角度
  50. line(mat, Point(line_[0], line_[1]), Point(line_[2], line_[3]), Scalar(0, 255, 0), 2, CV_AA);
  51. if (angle >= 0 && angle < 3.8)
  52. {
  53. begin_angle = 0;
  54. }
  55. if (angle >= 3.8 && angle < 87)
  56. {
  57. det_angle = angle;
  58. }
  59. if ((angle >= -90 && angle < -87) || (angle >= 87 && angle <= 90))
  60. {
  61. end_angle = angle;
  62. }
  63. }
  64. //imshow("霍夫直线检测",mat);
  65. waitKey(1);
  66. float resutValue =(det_angle/(abs(end_angle) - begin_angle)) * 300;
  67. return resutValue;
  68. }