【问题标题】:pixel encoding using PIL使用 PIL 进行像素编码
【发布时间】:2020-03-28 00:16:57
【问题描述】:

我有一个幼稚的问题,但经过漫长的一天后,我仍然无法得到答案。 我目前正在使用 PIL 加载我的 png 图像,它运行良好。但是,我的一些png 图像为每像素 16 位。我正在拼命地查询这些信息,但我无法使用 PIL 获取它。事实上,如果我只是使用file 系统二进制文件,它就可以工作。

$ file flower_16b.png 
flower_16b.png: PNG image data, 660 x 600, 16-bit/color RGB, non-interlaced

但是在我的 python 代码中:

img = Image.open(filename, "r")
print(img.mode)

我收到RGB。按照文档PIL RGB 表示(3x8 位像素,真彩色),看起来图像已被投射。那么它是否存在一种使用 PIL 或其他 python 模块来获取图像深度的方法?

【问题讨论】:

  • AFAIK 唯一的 16 位 PNG pixel format 是灰度的,因此声称您获得 RGB 是没有意义的。你也没有说为什么你需要深度信息……
  • @martineau 我认为 OP 的意思是 "Truecolor",即 3 个通道,每个通道 16 位,即链接表中的 48
  • 我正在运行推理问题。我的研究团队证明它仅适用于 8 位像素 png,但正如您所说,这是没有意义的,因为标准颜色是 8 位像素。

标签: python python-imaging-library


【解决方案1】:

PIL/Pillow 不会 support 那样的 48 位图像。一种选择可能是 OpenCV,但请注意它是 BGR 而不是 RGB:

import cv2

# Read with whatever bit depth is specified in the image file
BGR = cv2.imread('image.png', cv2.IMREAD_ANYDEPTH|cv2.IMREAD_ANYCOLOR)

# Check dtype and number of channels
print(BGR.dtype, BGR.shape)

dtype('uint16'), (768, 1024, 3)

另一个选项可能是pyvips,它的工作方式略有不同,但有一些好处:

import pyvips

im = pyvips.Image.new_from_file('image.png', access="sequential")

print(im)
<pyvips.Image 1024x768 ushort, 3 bands, rgb16>

如果您真的非常卡住并且不能/不会安装 OpenCVpyvips,您可以使用 ImageMagick强>...

您可以使用以下方法将 3 个 RGB 通道(每个 16 位)减少到 3 个 RGB 通道(每个 8 位):

magick input.png PNG24:output.png      # then open "output.png" with PIL

或者,您可以将 3 个 RGB 通道分成 3 个单独的 16 位文件,并使用 PIL/Pillow 分别处理它们:

magick input.png -separate channel-%d.png

您将在channel-0.png 中获得红色通道作为16 位图像,您可以使用PIL/Pillow 打开,绿色通道为channel-1.png,蓝色通道为channel-2.png

【讨论】:

  • 要将BGR转换为RGB,只需RGB = BGR[..., ::-1]
  • @Mark 非常感谢您提出的所有建议!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
相关资源
最近更新 更多