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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
namespace ShenTun.ImageCollection.AForgeCamera
{
public class ImageRectHelper
{
public static void AutoCutImage(string fileName,int topLeftX,int topLeftY,int bottomRightX,int bottonRightY)
{
using (Mat src = new Mat(fileName))
{
// 已知矩形的左上角和右下角坐标
Point topLeft = new Point(topLeftX, topLeftY); // x1, y1 是矩形左上角的坐标
Point bottomRight = new Point(bottomRightX, bottonRightY); // x2, y2 是矩形右下角的坐标
Rect rect = new Rect(topLeft.X, topLeft.Y, bottomRight.X - topLeft.X, bottomRight.Y - topLeft.Y);
// 检查坐标是否超出图像边界
if (rect.X < 0 || rect.Y < 0 || rect.Width <= 0 || rect.Height <= 0 ||
rect.X + rect.Width > src.Cols || rect.Y + rect.Height > src.Rows)
{
Console.WriteLine("指定的矩形坐标超出图像边界。");
return;
}
// 裁剪矩形区域
using (Mat crop = new Mat(src, rect))
{
// 保存裁剪后的图片
Cv2.ImWrite(fileName, crop);
}
}
}
// 检测轮廓是否为矩形的方法
private static bool IsRectangle(Point[] contour, double accuracy)
{
double arcLength = Cv2.ArcLength(contour, true);
Point[] approx = Cv2.ApproxPolyDP(contour, accuracy * arcLength, true);
return approx.Length == 4 && Cv2.IsContourConvex(approx);
}
}
}