Im using a hikvision color camera to grab images. I have been working with monochrome camera and the exisiting code that I have works well for 8bpp indexed pixel format. The camera has RGB8 pixel format.
My code to display images from monochrome camera is ;
using (Bitmap bmp1 = new Bitmap(stFrameInfo.stFrameInfo.nWidth, stFrameInfo.stFrameInfo.nHeight, stFrameInfo.stFrameInfo.nWidth, PixelFormat.Format8bppIndexed, stFrameInfo.pBufAddr))
{
ColorPalette cp = bmp1.Palette;
for (int i = 0; i < 256; i)
{
cp.Entries[i] = Color.FromArgb(i, i, i);
}
bmp1.Palette = cp;
this.Invoke((MethodInvoker)delegate
{
imageBox1.Image = bmp1;
});
But this shows a grayscale image full of lines with the color camera. How do I correct this to get proper color image?
CodePudding user response:
Your palette is not created correctly. Color.FromArgb(i, i, i)
will just set each palette color to a grayscale color, and that is probably not what you want.
RGB8 uses bits in the order:
Bit 7 6 5 4 3 2 1 0
Data R R R G G G B B
So to get the color value for each palette index you need to do some bit manipulation.
var r = (int)(byte.MaxValue * 8f / ((i >> 5) & 0b0000111))
var g = (int)(byte.MaxValue * 8f / ((i >> 2) & 0b0000111))
var b = (int)(byte.MaxValue * 4f / ((i >> 0) & 0b0000011))
I think that is correct, but I have not tested it, so I may have made some mistakes.
I would note that you use the width for both the width and the stride. This might be correct, but it is possible for the width and stride to differ, so it is common to have separate parameters for these. Might be worth doublechecking.
CodePudding user response:
You can modify the code as follows to handle RGB8 pixel format:
using (Bitmap bmp1 = new Bitmap(stFrameInfo.stFrameInfo.nWidth, stFrameInfo.stFrameInfo.nHeight, stFrameInfo.stFrameInfo.nWidth * 3, PixelFormat.Format24bppRgb, stFrameInfo.pBufAddr))
{
this.Invoke((MethodInvoker)delegate
{
imageBox1.Image = bmp1;
});
}
Note that the number of bits per pixel has changed from 8 to 24, and the pixel format has changed to Format24bppRgb, to reflect the color information in the RGB8 pixel format. Additionally, the stride has been multiplied by 3 to accommodate the extra color information.