1

I have a 16 bit ushort array with values ranging from 0 to 65535 which I want to convert into a grayscale Image to save. What I tried doing was write the values into an image data type and then converting the image to a bitmap, but as soon as I put it into the bitmap data type it gets converted to 8 bit data.

using (Image<Gray, ushort> DisplayImage2 = new Image<Gray, ushort>(Width, Height))
{
    int Counter = 0;
    for (int i = 0; i < Height; i++)
    {
        for (int j = 0; j < Width; j++)
        {
            DisplayImage.Data[i, j, 0] = ushortArray[Counter];
            Counter++;
        }
    }
    Bitmap bitt = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);
    bitt = DisplayImage2.ToBitmap();
    bitt.Save(SaveDirectory, System.Drawing.Imaging.ImageFormat.Tiff);)
}

As soon as the image gets put into the bitmap bitt it gets changed to 8 bit, is there a way of doing this? Thank you

Kokohne
  • 15
  • 5
  • I know, that's why I tried saving it as a 24bit too, but it ends up as 8 bit at the end too. – Kokohne Oct 18 '18 at 14:44
  • Show where you get this array, if it has any headings, any specific format. – Barmak Shemirani Oct 18 '18 at 15:00
  • The array comes from a camera frame grab and it is just values between 0 and 65535 nothing else. – Kokohne Oct 18 '18 at 15:11
  • It doesn't have to be tiff, just any file format that supports 16bit images. – Kokohne Oct 18 '18 at 16:04
  • Camera image is probably raw format, it has nothing to do with 16-bit bitmap format. 16-bit bitmap format is old and it loses color information. – Barmak Shemirani Oct 18 '18 at 19:07
  • 16-bit bitmap format is either RGB565 or RGB555, it's old and is not used in modern applications. You can store grayscale in 16-bit but that's less efficient than storing grayscale in 8-bit format. Show some information about your camera and print the first bytes in the source image. – Barmak Shemirani Oct 18 '18 at 19:42
  • Apparently there is a way to save a 16bit grayscale bitmap as TIFF after all: https://stackoverflow.com/a/40179536/555045 – harold Oct 18 '18 at 20:00

1 Answers1

0

Adapting from the linked answer on how to store a Format16bppGrayScale bitmap as TIFF, but without creating the actual bitmap first. This requires some .NET dlls that you may not usually add as references, namely PresentationCore and WindowsBase.

The BitmapSource necessary to construct the BitmapFrame that the TIFF encoder can encode can be created straight from an array, so:

var bitmapSrc = BitmapSource.Create(Width, Height, 96, 96,
                                    PixelFormats.Gray16, null, rawData, Width * 2);
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.Zip;
encoder.Frames.Add(BitmapFrame.Create(bitmapSrc));
encoder.Save(outputStream);

When I tried this, the file seemed to be a real 16bit image.

harold
  • 61,398
  • 6
  • 86
  • 164