How to convert Mat to Bitmap using OpenCVSharp?

I tried this first,

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

enter image description here

So 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 does not work either.

enter image description here

+7
image-processing opencvsharp
source share
2 answers

Instead of using the Mat type, I suggest using the IplImage type. Take the following code example as a link (I am using VisualStudio2013 with OpenCvSharp2):

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenCvSharp; using System.Drawing; namespace TestOpenCVSharp { class Program { static void Main(string[] args) { // Read the Lenna image IplImage inputImage = new IplImage(@"Lenna.png"); // Display the input image for visual inspection new CvWindow("original image", inputImage); Cv.WaitKey(); // Convert into bitmap Bitmap bitimg = MatToBitmap(img); // Save the bitmap bitimg.Save(@"bitmap.png"); } // end of main function // This is the function that converts IplImage image // into Bitmap public static Bitmap MatToBitmap(IplImage image) { return OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image); } // end of MatToBitmap function } // end of class definition } // end of namespace definition 

This is your Lenna image input:

enter image description here

And this is bitmap.png created from the Bitmap type:

enter image description here

Hope this helps!

Update:

Using OpenCVSharp3, the following code can also convert a Mat type to a Bitmap type:

 Mat image = new Mat(@"Lenna.png"); Cv2.ImShow("image", image); Cv2.WaitKey(); Bitmap bitimg = MatToBitmap(image); // Save the bitmap bitimg.Save(@"bitmap.png"); 

with function:

 public static Bitmap MatToBitmap(Mat image) { return OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image); } // end of MatToBitmap function 

And the result will be the same as shown above.

+8
source share

mat have a method that returns a bitmap:

  mat.ToBitmap(bitmap); 

"using OpenCvSharp.Extensions;" also necessary for this.

+1
source share

All Articles