Opencv中文网

任意角度旋转(GetRotationMatrix2D + WarpAffine)

组合算法:GetRotationMatrix2D + WarpAffine

GetRotationMatrix2D 参数

  • center:旋转中心点,默认图像中心
  • angle:旋转角度
    • 范围:-360 ~ 360
    • 正负效果:正数逆时针、负数顺时针
  • scale:缩放系数
    • 默认:1.0
    • 范围:0.1 ~ 2.0

WarpAffine:执行仿射旋转变换

使用场景

倾斜文本矫正、不规则倾斜工件摆正。

public override Mat Execute(Mat src)
{
    Mat dst = new Mat();
    Point2f center = new Point2f(src.Cols / 2f, src.Rows / 2f);

    // 1. 获取旋转矩阵
    Mat rotationMat = Cv2.GetRotationMatrix2D(center, Angle, Scale);

    Size outputSize = src.Size();

    if (AutoExpandCanvas)
    {
        Point2f[] pts = new Point2f[]
        {
            new Point2f(0, 0),
            new Point2f(src.Width, 0),
            new Point2f(0, src.Height),
            new Point2f(src.Width, src.Height)
        };

        Rect rect = Cv2.BoundingRect(pts);

        outputSize = new Size(rect.Width, rect.Height);

        // 修正中心点
        rotationMat.Set(0, 2, rotationMat.Get<double>(0, 2) + (rect.Width / 2f - center.X));
        rotationMat.Set(1, 2, rotationMat.Get<double>(1, 2) + (rect.Height / 2f - center.Y));
    }

    // 2. 执行仿射变换
    Cv2.WarpAffine(src, dst, rotationMat, outputSize, InterpolationFlag);

    rotationMat.Dispose();
    return dst;
}

copyright @重庆教主 WPF中文网 联系站长:(QQ)23611316 (微信)movieclip (QQ群).NET小白课堂:864486030 | 本文由WPF中文网原创发布,谢绝转载 渝ICP备2023009518号-1