OpenCV Mat和Bitmap的转换

最常用的方式是:

Cv2.ImRead() 可以将位图文件转成Mat数据格式
Cv2.ImWrite() 可以将Mat数据格式保存到位图文件.

不通过读写文件作为转换介质的方法:

private void testMatToPicture()
{
    var mat = Cv2.ImRead("D:\\my_workspace\\opencv\\images\\lena.jpg", ImreadModes.Color);

    //方法1: Mat -> Bitmap class
    Bitmap bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
    bitmap.Save("D:\\my_workspace\\opencv\\images\\1lena3.jpg", ImageFormat.Jpeg);

    //方法2: Mat -> byte[]
    byte[] bytes = mat.ToBytes(".jpg");            
    System.IO.File.WriteAllBytes("D:\\my_workspace\\opencv\\images\\1lena4.jpg", bytes);
}

private void testPictureToMat()
{
    // byte[] -> Mat
    var bytes = System.IO.File.ReadAllBytes("D:\\my_workspace\\opencv\\images\\lena.jpg");
    var colorMat = Mat.FromImageData(bytes, ImreadModes.Color);
    var grayMat = Mat.FromImageData(bytes, ImreadModes.Grayscale);

    // Bitmap class -> Mat
    Bitmap bitmap = new Bitmap("D:\\my_workspace\\opencv\\images\\lena.jpg");
    var mat2 = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);

    Cv2.ImShow("colorMat", colorMat);
    Cv2.ImShow("grayMat", grayMat);
    Cv2.ImShow("mat2", mat2);
    Cv2.WaitKey();
    Cv2.DestroyAllWindows();
    )
}
posted @ 2023-11-29 16:55  harrychinese  阅读(1702)  评论(0编辑  收藏  举报