python - 将单色 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”频道,但我认为这与我的问题有关。
解决方案
“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)
推荐阅读
- python - 如何在 Python 中绘制 3D 截断金字塔(使用用户输入)?
- entity-framework - 如何解决 entitychangetracker?
- c# - 找不到 SqlDataAdapter 类型或命名空间
- firebase - 从firebase(不是整个项目或数据库)中恢复意外删除的数据
- c++ - c ++ WebBrowser块url
- python - 在 Bokeh Google Map Offline 上重新绘制
- php - 多条 SQL 输出
- python-3.x - Create multiple objects from list of strings python
- c++ - 我应该为地图使用哪种数据结构?(C++)
- java - Android开发:ID在变量中时如何访问字符串?