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

标签 python numpy python-imaging-library

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

相关文章:

python - np.linalg.lstsq(X,Y)[0]-TypeError : No loop matching the specified signature and casting was found for ufunc lstsq_n

python - PIL Image Convert from RGB to YCbCr Results in 4 Channels 而不是 3 并且表现得像 RGB

python - PIL : add a text at the bottom middle of image

python - 使用 irc.bot.SingleServerIRCBot 保留线程(与 twitch 一起使用)

python - Travis-CI 找不到 python3-pip 包

python - "cannot concatenate ' str ' and ' list ' objects"不断出现 :(

python - 如何将 numpy 矩阵边界设置为零?

python - 向量化 NumPy 数组中的迭代加法

python - 如何使用 python 检测我的无线设备?

python - 如何使用图像哈希作为下载图像的文件名?