【问题标题】:Losing pixel depth when saving PNG image in C#在 C# 中保存 PNG 图像时丢失像素深度
【发布时间】:2018-12-12 00:47:30
【问题描述】:

我正在创建一个 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)

【问题讨论】:

  • 如果答案帮助你接受它!

标签: c# bitmap png grayscale 16-bit


【解决方案1】:

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

标志documentation 描述IMREAD_ANYDEPTH 如下:

如果设置,则在输入具有相应深度时返回 16 位/32 位图像,否则将其转换为 8 位。

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

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

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

【讨论】:

  • 感谢您解决了我的问题,img 对象现在显示如下:“dtype('uint16')”! :-)
猜你喜欢
  • 2011-09-13
  • 2016-05-17
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
相关资源
最近更新 更多