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

學無先后,達者為師

網站首頁 編程語言 正文

python的ImageTk.PhotoImage大坑及解決_python

作者:_less?is?more ? 更新時間: 2022-12-27 編程語言

python的ImageTk.PhotoImage大坑

如果大家遇到這樣的報錯:

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\數字實驗備份\結課實驗\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

網上很多教程的方法我也試過,沒有用,也調試不出為什么

這里有個很關鍵的信息:Cannot handle this data type

說明是數據的類型錯了,但再三檢查后,明明就是帶入的<class ‘numpy.ndarray’>類型

所以,大坑來了

請仔細檢查自己array里面每個數的類型,它必須是<class ‘numpy.uint8’>,否則就會報錯

可以這樣改:

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

Tkinter PhotoImage 踩坑記錄

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

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

解決辦法:使用PILLOW庫的ImageTk

  • 1.如果沒有安裝PILLOW插件,請安裝插件,使用 “pip install PILLOW”命令安裝即可
  • 2.生成PhotoImage對象:

代碼:

from PIL import Image

from PIL import ImageTk

img = Image.open(filePath)

img = ImageTk.PhotoImage(img)

2.PhotoImage顯示問題:顯示空白框,大小是圖片的真實大小

原因:見https://docs.Python.org/2/library/tkinter.html#images,說白了就是圖像數據引用被回收了圖片就顯示不出來了,只會顯示一個空box。

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

代碼:

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

欄目分類
最近更新