gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:21:35 25 4
gpt4 key购买 nike

我一直在尝试使用 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')

During handling of the above exception, another exception occurred:

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。请帮忙。

最佳答案

问题在于数据的形状。 Pillow 的fromarray 函数只能做一个MxNx3 数组(RGB 图像),或者一个MxN 数组(灰度)。要使灰度图像正常工作,您必须将 MxNx1 数组转换为 MxN 数组。您可以使用 np.reshape() 函数执行此操作。这会将数据展平,然后将其放入不同的数组形状。

IMIR = IMIR.reshape(M, N) #设 M 和 N 为图像的尺寸

(在 img = Image.fromarray(IMIR) 之前添加)

关于python - 将 numpy.array 对象转换为 PIL 图像对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51479140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com