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

pkwftd7m  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(75)

我有一个RGB数组,我想用fromarray导入PIL并保存到磁盘:

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对象中的uint8 RGB数组并保存为PNG?

注意:不是convert RGB arrays to PIL image的重复。
NB 2:我也尝试了RGBA数组,但结果是类似的(输出图像是Red Black Black Black而不是Red Green Blue Black):

a = np.array([[[255, 0, 0, 255], [0, 255, 0, 255]],     # Red   Green
              [[0, 0, 255, 255], [0, 0, 0, 255]]])      # Blue  Black
y4ekin9u

y4ekin9u1#

似乎你的数组需要是uint 8类型,那么一切都正常。
工作示例:

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)

干杯!干杯!

相关问题