How to convert WriteableBitmap in RGB24 format to EmguCV <Bgr, Byte> format?

I am trying to convert a WriteableBitmap that has Rgb24 as pixelFormat. I want to save the same image to an EmguCV image that has the Bgr format. I wrote the following code, but it does not give the corresponding results.

public unsafe void Convert(WriteableBitmap bitmap) { byte[] retVal = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4]; bitmap.CopyPixels(new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight), retVal, bitmap.PixelWidth * 4, 0); Bitmap b = new Bitmap(bitmap.PixelWidth, bitmap.PixelHeight); int k = 0; byte red, green, blue, alpha; for (int i = 0; i < bitmap.PixelWidth; i++) { for (int j = 0; j < bitmap.PixelHeight && k<retVal.Length; j++) { alpha = retVal[k++]; blue = retVal[k++]; green = retVal[k++]; red = retVal[k++]; System.Drawing.Color c = new System.Drawing.Color(); c = System.Drawing.Color.FromArgb(alpha, red, green, blue); b.SetPixel(i, j, c); } } currentFrame = new Image<Bgr, byte>(b); currentFrame.Save("Converted.jpg"); } 

Thanks in advance.

0
c # image image-processing emgucv writeablebitmap
source share
1 answer

Are you still getting this error? I finally got this working by dumping the data from the WriteableBitmap variable into a MemoryStream, and then from there into the Bitmap variable.

The following is an example: bitmap - WriteableBitmap variable

 BitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap); MemoryStream ms = new MemoryStream(); encoder.Save(ms); Bitmap b=new Bitmap(ms); Image<Bgr, Byte> image = new Image<Bgr, Byte>(b); 

I think this method is a better approach because you do not go through nested for loops, which can be much slower. Anyway, this will work for you.

+2
source share

All Articles