日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

python的ImageTk.PhotoImage大坑及解決_python

作者:_less?is?more ? 更新時(shí)間: 2022-12-27 編程語(yǔ)言

python的ImageTk.PhotoImage大坑

如果大家遇到這樣的報(bào)錯(cuò):

Exception in Tkinter callback
Traceback (most recent call last):
? File "E:\Anaconda3_files\lib\site-packages\PIL\Image.py", line 2515, in fromarray
? ? mode, rawmode = _fromarray_typemap[typekey]
KeyError: ((1, 1, 3), '<f8')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
? File "E:\Anaconda3_files\lib\tkinter\__init__.py", line 1705, in __call__
? ? return self.func(*args)
? File "D:\Junior Spring\Digital Image Processing and Experiment\數(shù)字實(shí)驗(yàn)備份\結(jié)課實(shí)驗(yàn)\ImgProcessing.py", line 806, in Sobel_Sharpening
? ? image = ImageTk.PhotoImage(Image.fromarray(img))
? File "E:\Anaconda3_files\lib\site-packages\PIL\Image.py", line 2517, in fromarray
? ? raise TypeError("Cannot handle this data type")
TypeError: Cannot handle this data type

網(wǎng)上很多教程的方法我也試過(guò),沒(méi)有用,也調(diào)試不出為什么

這里有個(gè)很關(guān)鍵的信息:Cannot handle this data type

說(shuō)明是數(shù)據(jù)的類型錯(cuò)了,但再三檢查后,明明就是帶入的<class ‘numpy.ndarray’>類型

所以,大坑來(lái)了

請(qǐng)仔細(xì)檢查自己array里面每個(gè)數(shù)的類型,它必須是<class ‘numpy.uint8’>,否則就會(huì)報(bào)錯(cuò)

可以這樣改:

dst = dst.astype(np.uint8)
image = ImageTk.PhotoImage(Image.fromarray(dst))

Tkinter PhotoImage 踩坑記錄

1.直接使用PhotoImage(file= ‘xxxx’)報(bào)錯(cuò):_tkinter.TclError: couldn’t recognize data in image file “xxxxx.png”

原因:PhotoImage支持的圖片格式有限。

解決辦法:使用PILLOW庫(kù)的ImageTk

  • 1.如果沒(méi)有安裝PILLOW插件,請(qǐng)安裝插件,使用 “pip install PILLOW”命令安裝即可
  • 2.生成PhotoImage對(duì)象:

代碼:

from PIL import Image

from PIL import ImageTk

img = Image.open(filePath)

img = ImageTk.PhotoImage(img)

2.PhotoImage顯示問(wèn)題:顯示空白框,大小是圖片的真實(shí)大小

原因:見(jiàn)https://docs.Python.org/2/library/tkinter.html#images,說(shuō)白了就是圖像數(shù)據(jù)引用被回收了圖片就顯示不出來(lái)了,只會(huì)顯示一個(gè)空box。

解決辦法:保存PhotoImage對(duì)象即可,示例代碼如下:

代碼:

imgDict = {}
def getImgWidget(filePath):

? ? if os.path.exists(filePath) and os.path.isfile(filePath):

? ? ? ? if filePath in imgDict and imgDict[filePath]:

? ? ? ? ? ? return imgDict[filePath]

? ? ? ? img = Image.open(filePath)

? ? ? ? #print(img.size)

? ? ? ? img = ImageTk.PhotoImage(img)

? ? ? ? imgDict[filePath] = img

? ? ? ? return img

? ? return None

原文鏈接:https://blog.csdn.net/weixin_42815846/article/details/106864921

欄目分類
最近更新