如何将RGB24像素格式的可写位图转换为EmguCV图像<Bgr,字节>格式?



我正在尝试转换具有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");
}

提前谢谢。

你仍然收到这个错误吗? 我最终通过将数据从 WriteableBitmap 变量转储到 MemoryStream 中,然后从那里转储到 Bitmap 变量中来解决这个问题。

下面是一个示例:位图是可写位图变量

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

我认为这种方式是一种更好的方法,因为您不必通过嵌套的 for 循环,这可能会慢得多。 无论如何,希望这对您有用

相关内容

最新更新