C# 图像旋转一定角度后,对应坐标怎么计算?

发布于:2024-04-27 ⋅ 阅读:(25) ⋅ 点赞:(0)

原理分析

要计算图像内坐标在旋转一定角度后的新坐标,可以使用二维空间中的点旋转公式。假设图像的中心点(即旋转中心)为 (Cx, Cy),通常对于正方形图像而言,中心点坐标为 (Width / 2, Height / 2)。给定原坐标点 (X, Y) 要绕中心点逆时针旋转角度 θ,其旋转后的坐标 (X', Y') 计算公式如下:

7489fb1a100f40b298511da4692de7e1.png

其中,θ 通常以弧度为单位。若已知角度而非弧度,则需先将其转换为弧度:

121fe4f22ae1498e88c7a4ed61a39a56.png

对于您提供的图像尺寸(宽3072,高3072),图像中心点坐标为 (1536, 1536)。假设您要旋转的角度为 θ 度,您可以按照以下步骤计算坐标 [0] 和 [1] 在旋转后的坐标:

  1. 确定旋转角度:确保角度 θ 已转换为弧度。
  2. 应用旋转公式fc950ec6bb8245faad6f7d45ced72531.png

计算上述公式即可得到旋转后坐标 [0] 和 [1] 的新坐标 (X'_0, Y'_0) 和 (X'_1, Y'_1)

请注意,旋转后的坐标可能会超出原图像边界,这取决于旋转角度。在实际编程应用中,可能需要结合图像旋转后的裁剪或插值处理来确保结果符合预期。

可以使用如GDI+或OpenCV等库提供的旋转功能,它们通常会自动处理边界问题和插值算法。如果您需要纯数学计算后的坐标用于其他目的,只需按照上述公式计算即可。

 

代码示例

using System;  
  
public class Point  
{  
    public int X { get; set; }  
    public int Y { get; set; }  
}  
  
public class Program  
{  
    public static void Main()  
    {  
        // 示例点  
        Point point1 = new Point { X = 1490, Y = 1200 };  
        Point point2 = new Point { X = 1931, Y = 2448 };  
  
        // 图像中心和旋转角度(以度为单位)  
        int centerX = 1536;  
        int centerY = 1536;  
        double rotationAngleInDegrees = 45; // 旋转45度  
  
        // 计算旋转后的坐标  
        Point rotatedPoint1 = RotatePoint(point1, centerX, centerY, rotationAngleInDegrees);  
        Point rotatedPoint2 = RotatePoint(point2, centerX, centerY, rotationAngleInDegrees);  
  
        // 输出结果  
        Console.WriteLine($"Rotated Point 1: X={rotatedPoint1.X}, Y={rotatedPoint1.Y}");  
        Console.WriteLine($"Rotated Point 2: X={rotatedPoint2.X}, Y={rotatedPoint2.Y}");  
    }  
  
    public static Point RotatePoint(Point point, int centerX, int centerY, double rotationAngleInDegrees)  
    {  
        // 将角度转换为弧度  
        double rotationAngleInRadians = rotationAngleInDegrees * (Math.PI / 180);  
  
        // 计算旋转后的坐标  
        int rotatedX = (int)((point.X - centerX) * Math.Cos(rotationAngleInRadians) - (point.Y - centerY) * Math.Sin(rotationAngleInRadians) + centerX);
        int rotatedY = (int)((point.X - centerX) * Math.Sin(rotationAngleInRadians) + (point.Y - centerY) * Math.Cos(rotationAngleInRadians) + centerY);
  
        return new Point { X = rotatedX, Y = rotatedY };  
    }  
}