如何使 img.show() 在 Pillow 中成为阻塞调用?
How to make img.show() a blocking call in Pillow?
我正在尝试查看由 Python 成像库生成的图像。在单独的进程中显示图像后使用以下代码段 returns。有没有办法显示图像并让 python 脚本块直到我关闭 window?
from PIL import Image
...
img = Image.open(...)
img.show()
我可以使用像 Qt 这样的 GUI 库来实现这一点。我不想添加它只是为了查看图像。
一个简单的 UI window 使用 tk 可以完成这个:
from PIL import Image, ImageTk
from tkinter import Tk, Label, BOTH
from tkinter.ttk import Frame, Style
class Example(Frame, object):
def __init__(self, parent):
Frame.__init__(self, parent)
self.pack(fill=BOTH, expand=1)
label1 = Label(self)
label1.photo= ImageTk.PhotoImage(Image.open(r"myImage"))
label1.config(image=label1.photo)
label1.pack(fill=BOTH, expand=1)
parent.mainloop()
Example(Tk())
注意:代码在 python 3 中,对于 python 2,导入会略有不同:
from Tkinter import Tk, Label, BOTH
from ttk import Frame, Style
Pillow 在后台显式启动其 Mac 和 Unix 查看器。幸运的是,Pillow 还公开了一种注册自定义查看器的方法,因此您可以覆盖此行为。
我个人用feh
:
import os
from PIL ImageShow
class FehViewer(ImageShow.UnixViewer):
def show_file(self, filename, **options):
os.system('feh %s' % filename)
return 1
ImageShow.register(FehViewer, order=-1)
[...]
实现阻塞调用的一种间接方法是在 matplotlib 中显示 PIL 图像:
import matplotlib.pyplot as plt
import numpy as np
import PIL
img = PIL.Image.open("image.jpg")
plt.imshow(np.asarray(img))
plt.show() # Default is a blocking call
我正在尝试查看由 Python 成像库生成的图像。在单独的进程中显示图像后使用以下代码段 returns。有没有办法显示图像并让 python 脚本块直到我关闭 window?
from PIL import Image
...
img = Image.open(...)
img.show()
我可以使用像 Qt 这样的 GUI 库来实现这一点。我不想添加它只是为了查看图像。
一个简单的 UI window 使用 tk 可以完成这个:
from PIL import Image, ImageTk
from tkinter import Tk, Label, BOTH
from tkinter.ttk import Frame, Style
class Example(Frame, object):
def __init__(self, parent):
Frame.__init__(self, parent)
self.pack(fill=BOTH, expand=1)
label1 = Label(self)
label1.photo= ImageTk.PhotoImage(Image.open(r"myImage"))
label1.config(image=label1.photo)
label1.pack(fill=BOTH, expand=1)
parent.mainloop()
Example(Tk())
注意:代码在 python 3 中,对于 python 2,导入会略有不同:
from Tkinter import Tk, Label, BOTH
from ttk import Frame, Style
Pillow 在后台显式启动其 Mac 和 Unix 查看器。幸运的是,Pillow 还公开了一种注册自定义查看器的方法,因此您可以覆盖此行为。
我个人用feh
:
import os
from PIL ImageShow
class FehViewer(ImageShow.UnixViewer):
def show_file(self, filename, **options):
os.system('feh %s' % filename)
return 1
ImageShow.register(FehViewer, order=-1)
[...]
实现阻塞调用的一种间接方法是在 matplotlib 中显示 PIL 图像:
import matplotlib.pyplot as plt
import numpy as np
import PIL
img = PIL.Image.open("image.jpg")
plt.imshow(np.asarray(img))
plt.show() # Default is a blocking call