C#+OpenCV基礎(四)_旋轉翻轉透視

꧁执笔小白꧂發表於2024-07-10

1、旋轉

/// <summary>
/// 旋轉圖片
/// </summary>
/// <param name="mat">圖片</param>
/// <param name="rotate">旋轉方向</param>
/// <returns></returns>
public static Mat Rotate(Mat mat, RotateFlags rotate)
{
    Mat result = new Mat();
    Cv2.Rotate(mat, result, rotate);
    return result;
}

/// <summary>
/// 任意角度旋轉圖片
/// </summary>
/// <param name="mat">圖片</param>
/// <param name="input">旋轉矩陣;</param>
/// <param name="dsize">輸出圖片大小</param>
/// <param name="flags">畫素插值方式</param>
/// <param name="borderMode">背景填充預設為常量</param>
/// <param name="borderValue">填充顏色預設為黑色</param>
/// <returns></returns>
public static Mat WarpAffine(Mat mat, InputArray input, Size dsize,
    InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null)
{
    Mat dst = new Mat();

    //Mat input = Cv2.GetRotationMatrix2D(new Point2f(mat.Cols/2f,mat.Rows/2f),45,0.6);
    Cv2.WarpAffine(mat, dst, input, dsize, flags, borderMode, borderValue);  // dsize=mat.Size()
    return dst;
}

2、翻轉

/// <summary>
/// 翻轉圖片
/// </summary>
/// <param name="mat">圖片</param>
/// <param name="flipCode">繞X/Y軸翻轉</param>
/// <returns></returns>
public static Mat Flip(Mat mat, FlipMode flipCode)
{
    Mat result = new Mat();
    Cv2.Flip(mat, result, flipCode);
    return result;
}

3、透視

/// <summary>
/// 透檢視片
/// </summary>
/// <param name="mat">圖片</param>
/// <param name="srcPoints">源影像中的 三角形頂點座標 Point2f[] srcPoints = new Point2f[]{ new Point2f(0,0), new Point2f(mat.Cols,0), new Point2f(0,mat.Rows)};</param>
/// <param name="dstPoints">目標影像中的 三角形頂點座標 Point2f[] dstPoints = new Point2f[]{ new Point2f(mat.Cols *0.00f,mat.Rows*0.33f), new Point2f(mat.Cols *0.85f,mat.Rows*0.25f), new Point2f(mat.Cols *0.15f,mat.Rows*0.70f)};</param>
/// <returns></returns>
public static Mat GetAffineTransform(Mat mat, Point2f[] srcPoints, Point2f[] dstPoints)
{
    Mat dst = new Mat();

    //Point2f[] srcPoints = new Point2f[]
    //{
    //    new Point2f(0,0),
    //    new Point2f(mat.Cols,0),
    //    new Point2f(0,mat.Rows)
    //};

    //Point2f[] dstPoints = new Point2f[]
    //{
    //    new Point2f(mat.Cols *0.00f,mat.Rows*0.33f),
    //    new Point2f(mat.Cols *0.85f,mat.Rows*0.25f),
    //    new Point2f(mat.Cols *0.15f,mat.Rows*0.70f)
    //};

    Mat input = Cv2.GetAffineTransform(srcPoints, dstPoints);
    Cv2.WarpAffine(mat, dst, input, mat.Size());  // dsize=mat.Size()
    return dst;
}

相關文章