首页 > 解决方案 > 将单色 png 读入 numpy 数组

问题描述

我正在尝试将单色 PNG 文件加载到 numpy 数组中。对于大多数 PNG 文件,下面的代码可以正常工作。但是,如果 PNG 文件仅包含一种颜色,则 numpy 数组中每个像素的 RGBA 值[0, 0, 0, 255]将导致黑色图像。在颜色“红色”的情况下,如何访问正确的 RGBA 值?例如[255, 0, 0, 255]

from PIL import image
import numpy as np

red_image = Image.open("red.png")
arr = np.asarray(red_image)

打电话时red_image.getBands(),我希望("R",)根据文档看到一个元组。相反,我看到("P",). 我还不知道什么是“P”频道,但我认为这与我的问题有关。

标签: pythonnumpyimage-processingpng

解决方案


“P”表示 PIL 模式处于“托盘化”状态。更多信息:PIL 中“P”和“L”模式下的图像有什么区别?.

从“P”转换为“RGBA”解决了我的问题。

from PIL import image
import numpy as np

red_image = Image.open("red.png")
red_image = red_image.convert("RGBA") # added this line
arr = np.asarray(red_image)

推荐阅读