首页 > 解决方案 > 将 numpy.array 对象转换为 PIL 图像对象

问题描述

我一直在尝试使用 Image.fromarray 将 numpy 数组转换为 PIL 图像,但它显示以下错误。

Traceback(最近一次调用最后一次):文件“C:\Users\Shri1008 Saurav Das\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py”,第 2428 行,在 fromarray 模式下, rawmode = _fromarray_typemap[typekey] 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 行,fromarray raise TypeError("Cannot handle this data type ") 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。请帮忙。

标签: pythonnumpypython-imaging-library

解决方案


问题是数据的形状。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)


推荐阅读