0

我正在尝试转换具有 Rgb24 作为 pixelFormat 的 WriteableBitmap。我想将相同的图像存储到具有 Bgr 格式的 EmguCV 图像中。我编写了以下代码,但没有给出适当的结果。

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");
}

提前致谢。

4

1 回答 1

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

于 2012-09-02T15:54:07.783 回答