Convert numpy.array object to PIL image object

2024/10/3 8:32:04

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 SauravDas\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py",line 2428, in fromarraymode, 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 SauravDas/AppData/Local/Programs/Python/Python36-32/projects/try.py", line13, 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 fromarrayraise 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, ImageTkhf = 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.

Answer

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))

https://en.xdnf.cn/q/70747.html

Related Q&A

Scheduling celery tasks with large ETA

I am currently experimenting with future tasks in celery using the ETA feature and a redis broker. One of the known issues with using a redis broker has to do with the visibility timeout:If a task isn’…

How to read out scroll wheel info from /dev/input/mice?

For a home robotics project I need to read out the raw mouse movement information. I partially succeeded in this by using the python script from this SO-answer. It basically reads out /dev/input/mice a…

Tell me why this does not end up with a timeout error (selenium 2 webdriver)?

from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWaitbrowser = webdriver.Firefox()browser.get("http://testsite.com")element = WebDriverWait(browser, 10).until…

PEP 8: comparison to True should be if cond is True: or if cond:

PyCharm is throwing a warning when I do np.where(temp == True)My full code:from numpy import where, arraya = array([[0.4682], [0.5318]]) b = array([[0.29828851, 0., 0.28676873, 0., 0., 0., 0., 0.288014…

Getting the title of youtube video in pytube3?

I am trying to build an app to download YouTube videos in python using pytube3. But I am unable to retrieve the title of the video. Here goes my code: from pytube import YouTube yt = YouTube(link) prin…

pandas - concat with columns of same categories turns to object

I want to concatenate two dataframes with category-type columns, by first adding the missing categories to each column.df = pd.DataFrame({"a": pd.Categorical(["foo", "foo"…

Python convert Excel File (xls or xlsx) to/from ODS

Ive been scouring the net to find a Python library or tool that can converts an Excel file to/from ODS format, but havent been able to come across anything. I need the ability to input and output data …

Select pandas frame rows based on two columns values

I wish to select some specific rows based on two column values. For example:d = {user : [1., 2., 3., 4] ,item : [5., 6., 7., 8.],f1 : [9., 16., 17., 18.], f2:[4,5,6,5], f3:[4,5,5,8]} df = pd.DataFrame(…

Using scipy sparse matrices to solve system of equations

This is a follow up to How to set up and solve simultaneous equations in python but I feel deserves its own reputation points for any answer.For a fixed integer n, I have a set of 2(n-1) simultaneous e…

Segmentation Fault in Pandas read_csv

I have Python 2.7.5 on Os X 10.9 with Pandas version 0.12.0-943-gaef5061. When I download this train.csv file and run read_csv, I get Segmentation Fault 11. I have experimented with the file encoding…