1、OpencvSharp 透视变换Cv2.WarpPerspective()
WarpPerspective()透视变换是将图片投影到一个新的视平面,也称作投影映射透视变换不能保证物体形状的“平行性”。
private void WarpPerspective()
{
var srcPoints = new Point2f[] //指定变换前的四角点 //手工测量的坐标位置,实际使用中可以通过鼠标获取
{
new Point2f(Points[0].X,Points[0].Y),
new Point2f(Points[1].X,Points[1].Y),
new Point2f(Points[3].X,Points[3].Y),
new Point2f(Points[2].X,Points[2].Y),
//new Point2f(0,0),
//new Point2f(src_img.Width-1,0),
//new Point2f(0,src_img.Height-1),
//new Point2f(src_img.Width-1,src_img.Height-1),
};
int x = Math.Abs(Points[0].X - Points[1].X);
int y = Math.Abs(Points[0].Y - Points[1].Y);
int width = (int)Math.Sqrt(x * x + y * y);
x = Math.Abs(Points[2].X - Points[1].X);
y = Math.Abs(Points[2].Y - Points[1].Y);
int height = (int)Math.Sqrt(x * x + y * y);
//OpenCvSharp.Size size = new OpenCvSharp.Size(width+100,height+100);
var dstPoints = new Point2f[] 指定变换后的四角点
{
new Point2f(Points[3].X,Points[0].Y),
new Point2f(Points[2].X,Points[0].Y),
new Point2f(Points[3].X,Points[3].Y),
new Point2f(Points[2].X,Points[3].Y),
//new Point2f(0,0),
//new Point2f(width,0),
//new Point2f(0,height),
//new Point2f(width,height),
};
try
{
Mat TransformMatrix = Cv2.GetPerspectiveTransform(srcPoints, dstPoints); //根据变换前后四个角点坐标,计算变换矩阵
Cv2.WarpPerspective(src_img, dst, TransformMatrix, src_img.Size()); //透视变换函数
picBoxShowDel.Image = dst.ToBitmap();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
顺时针依次选择4个点,进行转换: