简体   繁体   English

如何将 RGBA 元组的 2D 矩阵转换为 PIL 图像?

[英]How to convert 2D matrix of RGBA tuples into PIL Image?

Suppose if I have image img with contents:假设我有包含内容的图像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)]]

Is there's any way I can make PIL Image from it?有什么办法可以从中制作 PIL Image 吗?

I tried Image.fromarray(np.asarray(img)) and I got the following error:我尝试Image.fromarray(np.asarray(img))并收到以下错误:

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

How can I resolve it?我该如何解决? Also is there's any solution without the usage of numpy module?还有没有使用numpy模块的解决方案吗? Thanks in advance.提前致谢。

I think you want this (quite self explanatory from 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)

You need to explicitly set dtype of an array as np.uint8 to let the Image object generator know the format of input data.您需要将数组的 dtype 显式设置为 np.uint8 以让 Image object 生成器知道输入数据的格式。 And I would also recommend to specify the mode because I don't know how PIL choose between RGBA and CMYK when there are 4 channels.而且我还建议指定模式,因为当有 4 个通道时,我不知道 PIL 如何在 RGBA 和 CMYK 之间进行选择。 The solution is here:解决方案在这里:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM