c# - 在 C# 中保存 PNG 图像时丢失像素深度

标签 c# bitmap png grayscale 16-bit

我正在创建一个 16 位灰度图像并使用 C# 将其保存为 PNG。当我使用 GIMP 或 OpenCV 加载图像时,图像显示精度为 8 位而不是 16 位。你知道我的代码有什么问题吗?

1) 这是用于创建 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) 这是读取图片属性的Python代码:

import cv2
img = cv2.imread(image_path)

最佳答案

documentation 之后cv2.imread(filename, flags),你可以看到有一个可选的标志IMREAD_ANYDEPTH

国旗documentation描述 IMREAD_ANYDEPTH 如下:

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

除非您另有说明,否则 imread(..) 会将图像转换为 8 位深度。

我希望以下内容能够加载 16 位深度的图像。

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

关于c# - 在 C# 中保存 PNG 图像时丢失像素深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51159067/

相关文章:

android - 在不同的 drawable 文件夹中位图需要多少内存

r - 如何保存带有放大文本的 R 图

ios - iOS 中压缩 PNG 文件错误组

c# - 如何将输入从一个声卡重定向到另一个?

c# - 如何将Items添加到类类型的属性中

c# - 在 asp.net 中将上传的文件转换为位图图像

android - 在位图上写评论

node.js - 图像未保存在 Palm 设备上

C# 添加 XMLNode 到 XMLNodeList

c# - .NET 如何捏造 HttpContext 对象