簡體   English   中英

將numpy.array對象轉換為PIL圖像對象

[英]Convert numpy.array object to PIL image object

我一直在嘗試使用Image.fromarray將numpy數組轉換為PIL圖像,但它顯示以下錯誤。

追溯(最近一次通話):文件“ 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中引發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。請提供幫助。

問題在於數據的形狀。 枕頭的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM