C#+OpenCV基礎(三)_修改高寬剪下拼接縮放

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

1、獲取/設定圖片高寬

 /// <summary>
 /// 獲取圖片寬高
 /// </summary>
 /// <param name="mat">圖片</param>
 /// <returns></returns>
 public static (int w, int h) GetSize(Mat mat)
 {
     //Debug.WriteLine("寬:" + srcMat.Size().Width+",高:"+ srcMat.Size().Height);
     //Debug.WriteLine("寬2:" + srcMat.Width + ",高2:" + srcMat.Height);
     //Debug.WriteLine("寬Rows:" + srcMat.Rows + ",高Cols:" + srcMat.Cols);

     (int w, int h) value;
     value.w = mat.Width;
     value.h = mat.Height;
     return value;
 }

 /// <summary>
 /// 調整圖片寬高
 /// 縮放圖片
 /// </summary>
 /// <param name="mat">圖片</param>
 /// <returns></returns>
 public static Mat SetSize(Mat mat, int width, int height)
 {
     Mat result = new Mat();
     Cv2.Resize(mat, result, new OpenCvSharp.Size(width, height));
     return result;
 }

2、剪下

/// <summary>
/// 剪下圖片
/// </summary>
/// <param name="mat">圖片</param>
/// <param name="x">座標x</param>
/// <param name="y">座標y</param>
/// <param name="w">寬度</param>
/// <param name="h">高度</param>
/// <returns></returns>
public static Mat CutImage(Mat mat, int x, int y, int w, int h)
{
    // 設定區域
    Rect rect = new Rect(x, y, w, h);

    Mat dst = new Mat(mat, rect);  // 建立新圖片
    return dst;
}

3、拼接

/// <summary>
/// 拼接圖片
/// </summary>
/// <param name="mats">圖片集</param>
/// <param name="isH">是否是縱向拼接;true=縱向拼接,false=橫向拼接</param>
/// <returns></returns>
public static Mat Concat(Mat[] mats, bool isV)
{
    Mat dst = new Mat();

    if (isV)
    {
        Cv2.VConcat(mats, dst);
    }
    else
    {
        Cv2.HConcat(mats, dst);
    }
    return dst;
}

4、縮放(壓縮)

/// <summary>
/// 壓縮圖片
/// </summary>
/// <param name="mat">圖片</param>
/// <param name="multiple">高與寬的壓縮倍數;預設是2倍</param>
/// <returns></returns>
public static Mat CompressTo(Mat mat, int multiple = 2)
{
    // 建立壓縮圖片
    Mat result = new Mat();
    //壓縮
    Cv2.Resize(mat, result, new OpenCvSharp.Size(mat.Cols / multiple, mat.Rows / multiple));
    return result;
}

相關文章