我正在开发一个从相机设备获取图像的程序。这是我如何获取图像的事件。
private void StreamGrabber_ImageGrabbed(object sender, ImageGrabbedEventArgs e)
{
IGrabResult res = e.GrabResult;
byte[] pixels = res.PixelData as byte[];
pictureBox1.Image = ByteArrayToBitmap(pixels,res.Width,res.Height, PixelFormat.Format8bppIndexed);
//ImagePersistence.Save(ImageFileFormat.Jpeg, "tmp/tmp" + i + ".jpg", img);
}
我可以使用上面的代码获取像素数据数组。我可以直接用单行代码保存图像。
ImagePersistence.Save(ImageFileFormat.Jpeg, "tmp/tmp" + i + ".jpg", img);
现在我的问题从这里开始。我不想保存它,我只想从像素数据创建 Bitmap 对象并简单地显示在我的 pictureBox1 对象中。我有图像的像素数据,但无论如何我都无法正确获取图像。
这是 ByteArrayToBitmap 函数;
public Bitmap ByteArrayToBitmap(byte[] byteIn, int imwidth, int imheight, PixelFormat pixelformat)
{
Bitmap picOut = new Bitmap(imwidth, imheight, pixelformat);
BitmapData bmpData = picOut.LockBits(new Rectangle(0, 0, imwidth, imheight), ImageLockMode.WriteOnly, pixelformat);
IntPtr ptr = bmpData.Scan0;
Int32 psize = bmpData.Stride * imheight;
System.Runtime.InteropServices.Marshal.Copy(byteIn, 0, ptr, psize);
picOut.UnlockBits(bmpData);
return picOut;
}
这是图像的外观;
如您所见,图像很奇怪。首先我想是不是相机的问题。但我已经用它自己的程序试过了,Camera 工作得很好。我的代码出了点问题。
我正在从调试屏幕提供有用的信息;
图像尺寸为 3840x2748。
像素数据的字节数组大小为 10.552.320
我做了那个计算:3840*2748 = 10.552.320 图像不是灰度的,是RGB图像,
所以我认为像素数据包括8位索引像素。
我被这个问题困住了。我试图为您提供有关我的问题的所有有用信息。
如何正确获取图像并创建位图对象?
编辑
public Bitmap CopyDataToBitmap(int Width, int Height, byte[] data)
{
var b = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
ColorPalette ncp = b.Palette;
int counter = 0;
for (int i = 32; i <= 256; i+=32) //for R channel (3 bit)
for (int j = 32; j <= 256; j+=32) //for G Channel (3 bit)
for (int k = 64; k <= 256; k+=64) //for B Channel (2 bit)
{
ncp.Entries[counter] = Color.FromArgb(255,i-1,j-1,k-1);
counter++;
}
b.Palette = ncp;
var BoundsRect = new Rectangle(0, 0, Width, Height);
BitmapData bmpData = b.LockBits(BoundsRect,
ImageLockMode.WriteOnly,
PixelFormat.Format8bppIndexed);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride * b.Height;
var rgbValues = new byte[bytes];
Marshal.Copy(data, 0, ptr, bytes);
b.UnlockBits(bmpData);
Console.WriteLine(b.GetPixel(3648, 1145).ToString());
return b;
}
我已经用那个函数改变了算法。我正在使用调色板。但结果还是一样。
ColorPalette ncp = b.Palette;
for (int i = 0; i < 257; i++)
ncp.Entries[i] = Color.FromArgb(255, i, i, i);
b.Palette = ncp;
当我使用这个调色板时,这一次,图像变成灰度。
我只想获得清晰的 RGB 图像。
编辑 2
我的相机的像素格式是 BayerBG8。我不知道它是否有帮助。
