python - 将 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。请帮忙。
解决方案
问题是数据的形状。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)
)
推荐阅读
- ios - 数组映射,斯威夫特
- sql - 在不使用临时表/外部表概念的情况下从文本/xls 文件获取更新/删除 SQL 语句的输入的最简单方法
- mongodb - 我想将 bcrypt.compare 与 mongoose/mongo enginee 搜索一起使用
- jquery - 模态弹出窗口,并在新选项卡中打开一个链接
- android - 为 Unity 上的 3D 角色添加适用于 Android 的操纵杆和触摸控件
- c - CS50 C 发出错误:数组初始值设定项必须是初始值设定项列表或字符串文字
- reactjs - 使用过滤器和挂钩的搜索功能
- kotlin - 未解决的参考:Github 上 Kotlin 和 Gradle 的 javafx
- asp.net-mvc - 是否可以在单个 _Layout.cshtml 中逐行显示多个局部视图?
- reactjs - 如何通过动态导入开始工作 React.lazy/Suspense?