Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy.array object to PIL image object

Tags:

I have been trying to convert a numpy array to PIL image using Image.fromarray but it shows the following error.

Traceback (most recent call last): File "C:\Users\Shri1008 Saurav Das\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py", line 2428, in fromarray mode, rawmode = _fromarray_typemap[typekey] KeyError: ((1, 1, 3062), '|u1')

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:/Users/Shri1008 Saurav Das/AppData/Local/Programs/Python/Python36-32/projects/try.py", line 13, in img = Image.fromarray(IMIR) File "C:\Users\Shri1008 Saurav Das\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py", line 2431, in fromarray raise TypeError("Cannot handle this data type") TypeError: Cannot handle this data type

I extracted the matrix from an hdf5 file and converted it to a numpy array. I then did some basic transformations to enhance contrast(most probable reason for error). Here is the code.

import tkinter as tk
import h5py as hp
import numpy as np
from PIL import Image, ImageTk

hf = hp.File('3RIMG_13JUL2018_0015_L1C_SGP.h5', 'r')
IMIR = hf.get('IMG_MIR')
IMIR = np.uint8(np.power(np.double(np.array(IMIR)),4)/5000000000)
IMIR = np.array(IMIR)

root = tk.Tk()
img = Image.fromarray(IMIR)
photo = ImageTk.PhotoImage(file = img)
cv = tk.Canvas(root, width=photo.width(), height=photo.height())
cv.create_image(1,1,anchor="nw",image=photo)

I am running Python 3.6 on Windows 10. Please help.

like image 547
Incognito Possum Avatar asked Jul 23 '18 12:07

Incognito Possum


1 Answers

The problem is the shape of your data. Pillow's fromarray function can only do a MxNx3 array (RGB image), or an MxN array (grayscale). To make the grayscale image work, you have to turn you MxNx1 array into a MxN array. You can do this by using the np.reshape() function. This will flatten out the data and then put it into a different array shape.

IMIR = IMIR.reshape(M, N) #let M and N be the dimensions of your image

(add this before the img = Image.fromarray(IMIR))

like image 181
Teige Needs some help pls Avatar answered Oct 11 '22 15:10

Teige Needs some help pls