代码之家  ›  专栏  ›  技术社区  ›  Basj

使用fromarray将RGB阵列导入PIL图像

  •  1
  • Basj  · 技术社区  · 2 年前

    我有一个要导入的RGB数组 PIL 具有 fromarray 并保存到磁盘:

    import numpy as np
    from PIL import Image
    from PIL.PngImagePlugin import PngInfo
    a = np.array([[[255, 0, 0], [0, 255, 0]],     # Red   Green
                  [[0, 0, 255], [0, 0, 0]]])      # Blue  Black  
    img = Image.fromarray(a, mode="RGB")   
    metadata = PngInfo()                    # I need to add metadata, thus the use of Pillow and **not cv2**
    metadata.add_text("key", "value")
    img.save("test.png", pnginfo=metadata)
    

    但是输出图像是 Red Black Black Black 而不是 Red Green Blue Black

    为什么?

    如何在PIL对象中正确导入uint8RGB数组并将其保存为PNG?

    注意:不是的副本 convert RGB arrays to PIL image

    NB2:我也尝试过RGBA阵列,但结果相似(输出图像为 红-黑-黑 而不是 红-绿-蓝-黑 )与:

    a = np.array([[[255, 0, 0, 255], [0, 255, 0, 255]],     # Red   Green
                  [[0, 0, 255, 255], [0, 0, 0, 255]]])      # Blue  Black  
    
    1 回复  |  直到 2 年前
        1
  •  3
  •   Prezt    2 年前

    似乎你的数组需要是uint8类型,然后一切都正常。

    工作示例:

    import numpy as np
    from PIL import Image
    from PIL.PngImagePlugin import PngInfo
    a = np.array([[[255, 0, 0], [0, 255, 0]],     # Red   Green
                  [[0, 0, 255], [0, 0, 0]]],      # Blue  Black
                 dtype=np.uint8)      
    img = Image.fromarray(a).convert("RGB")
    metadata = PngInfo()                    # I need to add metadata, thus the use of Pillow and **not cv2**
    metadata.add_text("key", "value")
    img.save("test.png", pnginfo=metadata)
    

    干杯