Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert Mat to Bitmap using OpenCVSharp?

First, I tried this,

    public static Bitmap MatToBitmap(Mat mat)
    {
        return OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
    }

enter image description here

So, then, I tried this,

    public static Bitmap MatToBitmap(Mat mat)
    {
        mat.ConvertTo(mat, MatType.CV_8U);
        return OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
    }

The image is completely black,

enter image description here

    public static Bitmap ConvertMatToBitmap(Mat matToConvert) 
    {            
        return new Bitmap(matToConvert.Cols, matToConvert.Rows, 4*matToConvert.Rows, System.Drawing.Imaging.PixelFormat.Format8bppIndexed, matToConvert.Data);
    }

This doesn't work either.

enter image description here

like image 737
user366312 Avatar asked May 31 '16 08:05

user366312


2 Answers

The others solutions almost worked for me. The bitmaps were there, but sometimes an exception saying that the encoder was null was threw.

I solved using the following code.

private static Bitmap MatToBitmap(Mat mat) {
    using (var ms = mat.ToMemoryStream()) {
        return (Bitmap) Image.FromStream(ms);
    }
}
like image 109
D.Kastier Avatar answered Oct 23 '22 18:10

D.Kastier


mat have a method that return Bitmap:

        mat.ToBitmap(bitmap);

"using OpenCvSharp.Extensions;" is also needed for this.

like image 38
Mohammad Roshani Avatar answered Oct 23 '22 19:10

Mohammad Roshani