【问题标题】:read a single color png into a numpy array将单色 png 读入 numpy 数组
【发布时间】:2021-12-13 20:53:41
【问题描述】:

我正在尝试将单色 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",) 的元组,就像documentation 一样。相反,我看到的是("P",)。我还不知道什么是“P”频道,但我认为这与我的问题有关。

【问题讨论】:

    标签: python numpy image-processing png


    【解决方案1】:

    “P”表示 PIL 模式处于“托盘化”状态。更多信息在这里:What is the difference between images in 'P' and 'L' mode in PIL?

    从“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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 2018-03-25
      • 1970-01-01
      • 2019-01-04
      • 2017-12-23
      • 2021-05-30
      • 2015-10-01
      相关资源
      最近更新 更多