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

Viewed 159

Suppose if I have image img with contents:

[[(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?

I tried Image.fromarray(np.asarray(img)) and I got the following error:

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? Thanks in advance.

2 Answers

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. 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. The solution is here:

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