我一直试图使用Image.fromarray将numpy数组转换为PIL图像,但它显示了以下错误。
原始回溯(最近一次调用):文件"C:\Users\Shri1008 Saurav Das\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py",line 2428,in fromarray mode,
= _fromarray_typemaptypekey KeyError:((1,1,3062),'|u1')
在处理上述异常的过程中,发生了另一个异常:
回溯(最近一次调用):文件"C:/Users/Shri1008 Saurav Das/AppData/Local/Programs/Python/Python36-32/projects/try.py",行13,在img = Image.fromarray(IMIR)文件"C:\Users\Shri1008 Saurav Das\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py",行2431,in fromarray raise TypeError(“无法处理此数据类型”) TypeError:无法处理此数据类型
我从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。请帮助。
发布于 2019-05-30 07:34:17
问题出在数据的形状上。Pillow的fromarray
函数只能做MxNx3数组(RGB图像)或MxN数组(灰度)。要使灰度图像工作,您必须将MxNx1数组转换为MxN数组。您可以使用np.reshape()
函数来完成此操作。这将展平数据,然后将其放入不同的数组形状中。
IMIR = IMIR.reshape(M, N) #let M and N be the dimensions of your image
(在img = Image.fromarray(IMIR)
之前添加此内容)
https://stackoverflow.com/questions/51479140
复制相似问题