Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read image from numpy array into PIL Image?

I am trying to read an image from a numpy array using PIL, by doing the following:

from PIL import Image
import numpy as np
#img is a np array with shape (3,256,256)
Image.fromarray(img)

and am getting the following error:

File "...Image.py", line 2155, in fromarray
    raise TypeError("Cannot handle this data type")

I think this is because fromarray expects the shape to be (height, width, num_channels) however the array I have is in the shape (num_channels, height, width) as it is stored in this was in an lmdb database.

How can I reshape the Image so that it is compatible with Image.fromarray?

like image 493
Aly Avatar asked May 20 '15 09:05

Aly


2 Answers

Try

img = np.reshape(256, 256, 3)
Image.fromarray(img)
like image 168
Ryan Avatar answered Oct 19 '22 16:10

Ryan


You don't need to reshape. This is what rollaxis is for:

Image.fromarray(np.rollaxis(img, 0,3))
like image 29
Lanting Avatar answered Oct 19 '22 16:10

Lanting