You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.8 KiB

1 month ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using OpenCvSharp;
  7. namespace ShenTun.ImageCollection.AForgeCamera
  8. {
  9. public class ImageRectHelper
  10. {
  11. public static void AutoCutImage(string fileName,int topLeftX,int topLeftY,int bottomRightX,int bottonRightY)
  12. {
  13. using (Mat src = new Mat(fileName))
  14. {
  15. // 已知矩形的左上角和右下角坐标
  16. Point topLeft = new Point(topLeftX, topLeftY); // x1, y1 是矩形左上角的坐标
  17. Point bottomRight = new Point(bottomRightX, bottonRightY); // x2, y2 是矩形右下角的坐标
  18. Rect rect = new Rect(topLeft.X, topLeft.Y, bottomRight.X - topLeft.X, bottomRight.Y - topLeft.Y);
  19. // 检查坐标是否超出图像边界
  20. if (rect.X < 0 || rect.Y < 0 || rect.Width <= 0 || rect.Height <= 0 ||
  21. rect.X + rect.Width > src.Cols || rect.Y + rect.Height > src.Rows)
  22. {
  23. Console.WriteLine("指定的矩形坐标超出图像边界。");
  24. return;
  25. }
  26. // 裁剪矩形区域
  27. using (Mat crop = new Mat(src, rect))
  28. {
  29. // 保存裁剪后的图片
  30. Cv2.ImWrite(fileName, crop);
  31. }
  32. }
  33. }
  34. // 检测轮廓是否为矩形的方法
  35. private static bool IsRectangle(Point[] contour, double accuracy)
  36. {
  37. double arcLength = Cv2.ArcLength(contour, true);
  38. Point[] approx = Cv2.ApproxPolyDP(contour, accuracy * arcLength, true);
  39. return approx.Length == 4 && Cv2.IsContourConvex(approx);
  40. }
  41. }
  42. }