Program.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using OpenCvSharp;
  2. using System;
  3. namespace ImageOcr
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. Mat img = new Mat();
  10. img = Cv2.ImRead("F:/IMG_20200927_150909.jpg");
  11. Cv2.ImShow("src", img);
  12. Mat grayImage = new Mat();
  13. Cv2.CvtColor(img, grayImage, ColorConversionCodes.BGR2GRAY);
  14. var Width= grayImage.Width;
  15. var Height = grayImage.Height;
  16. Mat binaryImage = new Mat();
  17. Cv2.AdaptiveThreshold(grayImage, binaryImage,255, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.Binary,35,10);
  18. Cv2.ImShow("binaryImage", binaryImage);
  19. Mat hierarchy = new Mat();
  20. Cv2.FindContours(binaryImage,out Mat[] contours, hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
  21. Cv2.DrawContours(img, contours, 0, new Scalar(0,0,255),1);
  22. Cv2.ImShow("imgray", img);
  23. foreach (var i in contours) {
  24. double arclen = Cv2.ArcLength( i, true);
  25. double epsilon = Math.Max(2, arclen * 0.02);
  26. Mat approx = new Mat();
  27. Cv2.ApproxPolyDP(i, approx, epsilon, true);
  28. double area =Cv2.ContourArea(i);
  29. Console.WriteLine("面积:" + area);
  30. RotatedRect rect = Cv2.MinAreaRect(i);
  31. Console.WriteLine("rect:" + rect);
  32. Point2f[] re= Cv2.BoxPoints(rect);
  33. var w = re[1].X;
  34. var h = re[1].Y;
  35. var rotion = 0F;
  36. if (Math.Min(h, w) == 0)
  37. {
  38. rotion = 0;
  39. }
  40. else {
  41. rotion = Math.Max(h, w) / Math.Min(h, w);
  42. }
  43. var imageArea = Width * Height;
  44. if(rotion<10 && area>imageArea*0.2 && area< Width* Height * 0.99 && approx==4)
  45. }
  46. }
  47. }
  48. }