First, I tried this,
public static Bitmap MatToBitmap(Mat mat)
{
return OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
}
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,
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.
Instead of using Mat
type, I suggest you to use IplImage
type. Take the following example code as reference (I use 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 input Lenna image:
And this is the bitmap.png
that is created from Bitmap
type:
Hope it helps!
Update:
By using OpenCVSharp3, the following code can also convert a Mat
type into 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 the function:
public static Bitmap MatToBitmap(Mat image)
{
return OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image);
} // end of MatToBitmap function
And the obtained result is the same as shown above.