欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python的ImageTk.PhotoImage大坑及解決

 更新時(shí)間:2022年11月30日 16:37:02   作者:_less is more  
這篇文章主要介紹了python的ImageTk.PhotoImage大坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

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)上很多教程的方法我也試過,沒有用,也調(diào)試不出為什么

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

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

所以,大坑來了

請(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庫的ImageTk

  • 1.如果沒有安裝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顯示問題:顯示空白框,大小是圖片的真實(shí)大小

原因:見https://docs.Python.org/2/library/tkinter.html#images,說白了就是圖像數(shù)據(jù)引用被回收了圖片就顯示不出來了,只會(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

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論