将numpy.array对象转换为PIL图像对象

7
我一直试图使用Image.fromarray将numpy数组转换为PIL图像,但会出现以下错误。
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')
在处理上述异常时,发生了另一个异常:
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 我从一个hdf5文件中提取了矩阵,并将其转换为numpy数组。然后我进行了一些基本的转换来增强对比度(这可能是错误的最有可能的原因)。以下是代码。
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)

我在Windows 10上运行Python 3.6,请帮忙。


1
PIL需要一个合理的数据类型的MxN(x3)数组。你传递了什么? - Mad Physicist
这是一个MN1矩阵(因此为灰度),我已经使用/5000000000将其调整到0-255的范围内,适用于uint8类型。 - Incognito Possum
如果需要,这是数据集 [DATASET LINK] 的链接 (https://drive.google.com/file/d/1UX8GyztY1OWgQIQbFUhl8lO4CH-7-ZjW/view?usp=sharing)。 - Incognito Possum
1个回答

5
问题在于你的数据形状。Pillow中的fromarray函数只能处理MxNx3数组(RGB图像)或MxN数组(灰度图像)。要使灰度图像正常工作,您必须将MxNx1数组转换为MxN数组。您可以使用np.reshape()函数来实现这一点。这将展平数据,然后将其放入不同的数组形状中。 IMIR = IMIR.reshape(M, N) #假设M和N是您图像的尺寸 (在img = Image.fromarray(IMIR)之前添加此代码)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接