【问题标题】:Display image converted to numpy array in Tkinter with PIL使用 PIL 在 Tkinter 中显示图像转换为 numpy 数组
【发布时间】:2018-05-08 18:00:48
【问题描述】:

我想用 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

它似乎找到了它 (&lt;PIL.Image.Image image mode=RGB size=295x400 at 0x28CAB9F5630&gt;),但由于某种原因打印它不存在。谁能建议可能导致此问题的原因?

【问题讨论】:

  • tkinter 无法显示Image - 它只能显示ImageTk.PhotoImage()

标签: python arrays numpy tkinter pillow


【解决方案1】:

虽然这个问题似乎已解决,但我想添加一个链接到“波纹坦克模拟器”,它可以实时更新 TkInter 画布,支持颜色图、浮雕、(取消)缩放等。

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

它仅取决于 TkInter + numpy。我试图优化它以提高速度,但又不会让它过于复杂。

【讨论】:

    【解决方案2】:

    我解决了这样的问题:

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

    【讨论】:

    • PIL 现在似乎被维护为枕头。我不得不点安装枕头(而不是 PIL)
    猜你喜欢
    • 2017-06-25
    • 1970-01-01
    • 2010-09-27
    • 2019-11-29
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多