簡體   English   中英

使用 PIL 在 Tkinter 中顯示轉換為 numpy 數組的圖像

[英]Display image converted to numpy array in Tkinter with PIL

我想用 PIL 加載圖像,然后將其轉換為數組(用於進一步操作),然后將其轉換回圖像並在 Tkinter Label 元素中顯示。 我有以下代碼:

from tkinter import *
import PIL as pl
from PIL import ImageTk, Image
import numpy as np

root = Tk()
root_panel = Frame(root)
root_panel.pack(side="bottom", fill="both", expand="yes")

img_src = 'pic.jpg'
img = pl.Image.open(img_src)
img_arr = np.array(img)
img = pl.Image.fromarray(img_arr)

img_panel = Label(root_panel)
img_panel.configure(image=img)
img_panel.pack(side="bottom", fill="both", expand="yes")

root.mainloop()

當我運行它時出錯:

File "C:/Users/lazar/Documents/GitHub/Face-Features-Detection/ui.py", line 19, in <module>
    img_panel.configure(image=img)
  File "C:\Users\a\Miniconda3\lib\tkinter\__init__.py", line 1479, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Users\a\Miniconda3\lib\tkinter\__init__.py", line 1470, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "<PIL.Image.Image image mode=RGB size=295x400 at 0x28CAB9F5630>" doesn't exist

它似乎找到了( <PIL.Image.Image image mode=RGB size=295x400 at 0x28CAB9F5630> ),但由於某種原因打印它不存在。 任何人都可以請建議可能導致此問題的原因嗎?

我解決了這樣的問題:

img_tk = ImageTk.PhotoImage(img)
img_panel = Label(root_panel)
img_panel.configure(image=img_tk)

雖然這個問題似乎已解決,但我想添加一個指向“波紋坦克模擬器”的鏈接,該鏈接實時更新 TkInter 畫布,支持顏色圖、浮雕、(取消)縮放等。

https://gist.github.com/FilipDominec/14761052f42d80d283bd3adcf7eb5347

它僅取決於 TkInter + numpy。 我試圖優化它的速度而不讓它過於復雜。

暫無
暫無

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

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