【问题标题】:How to convert 2D matrix of RGBA tuples into PIL Image?如何将 RGBA 元组的 2D 矩阵转换为 PIL 图像?
【发布时间】:2020-07-29 23:35:58
【问题描述】:

假设我有图片img 的内容:

[[(255, 255, 255, 255), (0, 0, 0, 255), (0, 0, 0, 255), (0, 0, 0, 255)],
 [(0, 0, 0, 255), (255, 255, 255, 255), (0, 0, 0, 255), (0, 0, 0, 255)],
 [(0, 0, 0, 255), (0, 0, 0, 255), (255, 255, 255, 255), (0, 0, 0, 255)],
 [(0, 0, 0, 255), (0, 0, 0, 255), (0, 0, 0, 255), (255, 255, 255, 255)]]

有什么方法可以制作 PIL Image 吗?

我尝试了Image.fromarray(np.asarray(img)),但出现以下错误:

TypeError: Cannot handle this data type: (1, 1, 4), <i4

我该如何解决?还有没有不使用numpy 模块的解决方案吗?提前致谢。

【问题讨论】:

  • 试试Image.fromarray(np.array(img), mode="RGBA")?

标签: python numpy python-imaging-library


【解决方案1】:

我想你想要这个(the doc 非常自我解释):

from PIL import Image

arr = np.array(img)
PIL_image = Image.frombuffer('RGBA',(arr.shape[0],arr.shape[1]),np.uint8(arr.reshape(arr.shape[0]*arr.shape[1],arr.shape[2])),'raw','RGBA',0,1)

【讨论】:

  • 它不符合我的期望,它使用问题中的数据生成了一个空白图像。
  • @JimmyYang 你的图片是什么模式?不是“RGBA”吗?试试我在帖子上的更新。可能是数据类型问题。
【解决方案2】:

您需要将数组的 dtype 显式设置为 np.uint8 以让 Image 对象生成器知道输入数据的格式。而且我还建议指定模式,因为当有 4 个通道时,我不知道 PIL 如何在 RGBA 和 CMYK 之间进行选择。解决方法在这里:

from PIL import Image
    
Image.fromarray(np.asarray(img, dtype=np.uint8), mode='RGBA')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多