How to read image from numpy array into PIL Image?
Asked Answered
A

3

17

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?

Arielariela answered 20/5, 2015 at 9:39 Comment(2)
maybe try Image.fromarray(np.uint8(img))Ingaborg
The type of array is uint8, the problem is in the shapeArielariela
B
15

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

Image.fromarray(np.rollaxis(img, 0,3))
Barbarossa answered 20/5, 2015 at 10:21 Comment(1)
This. A [C, H, W] array will be rolled to [H, W, C]. Note that it will work only when len(shape) == 3Plumbo
I
5

Try

img = np.reshape(256, 256, 3)
Image.fromarray(img)
Ingaborg answered 20/5, 2015 at 10:19 Comment(0)
L
1

Defining the datatype of the numpy array to np.uint8 fixed it for me.

>>> img = np.full((256, 256), 3)
>>> Image.fromarray(img)
...
line 2753, in fromarray
raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e
TypeError: Cannot handle this data type: (1, 1), <i8

So defining the array with the proper datatype:

>>> img = np.full((256, 256), 3, dtype=np.uint8)
>>> Image.fromarray(img)
<PIL.Image.Image image mode=L size=256x256 at 0x7F346EA31130>

creates the Image object successfully

Or you could simply modify the existing numpy array:

img = img.astype(np.uint8)
Lissalissak answered 24/12, 2020 at 0:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.