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

时间:2020-07-29 23:35:58

标签: python numpy python-imaging-library

假设我的图片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.fromarray(np.asarray(img)),但遇到以下错误:

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

我该如何解决?还有没有使用numpy模块的解决方案吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

我想你想要这个(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)