简体   繁体   中英

Losing pixel depth when saving PNG image in C#

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)

Following the documentation of cv2.imread(filename, flags) , you can see that there is an optional flag of IMREAD_ANYDEPTH .

The flag documentation describes IMREAD_ANYDEPTH as follows:

If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.

This states that imread(..) converts the image to 8-bit depth unless you specify otherwise.

I would expect the following to load the image with 16-bit depth.

img = cv2.imread(image_path, cv2.IMREAD_ANYDEPTH)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM