I am creating a 16-bit grayscale image and saving it as a PNG using C#. When I load the image using GIMP or OpenCV, the image appears with a precision of 8-bit instead of 16-bit. Do you know what is wrong with my code?
1) This is the code used to create the PNG
public static void Create16BitGrayscaleImage(int imageWidthInPixels, int imageHeightInPixels, ushort[,] colours,
string imageFilePath)
{
// Multiplying by 2 because it has two bytes per pixel
ushort[] pixelData = new ushort[imageWidthInPixels * imageHeightInPixels * 2];
for (int y = 0; y < imageHeightInPixels; ++y)
{
for (int x = 0; x < imageWidthInPixels; ++x)
{
int index = y * imageWidthInPixels + x;
pixelData[index] = colours[x, y];
}
}
BitmapSource bmpSource = BitmapSource.Create(imageWidthInPixels, imageHeightInPixels, 86, 86,
PixelFormats.Gray16, null, pixelData, imageWidthInPixels * 2);
using (Stream str = new FileStream(imageFilePath, FileMode.Create))
{
PngBitmapEncoder enc = new PngBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bmpSource));
enc.Save(str);
}
}
2) This is a Python code to read the image properties:
import cv2
img = cv2.imread(image_path)