How to convert WriteableBitmap in RGB24 pixel format into a EmguCV image<Bgr, Byte> format?
Asked Answered
T

1

0

I am trying to convert a WriteableBitmap which is having Rgb24 as a pixelFormat. I want to store the same image into a EmguCV Image having Bgr format. I have written a following code but it is not giving appropriate 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.

Thirtythree answered 26/4, 2012 at 13:10 Comment(0)
P
2

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 a Bitmap variable.

Below is an example: bitmap is the 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 way is a better approach because you don't have go through the nested for loops which could be far slower. Anyway hope this works for you

Peridot answered 2/9, 2012 at 15:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.