我正在使用PIL库进行图像编辑。问题是,我不想每次将图像保存到硬盘上,再在资源管理器中查看。有没有一个简单的模块可以让我设置一个窗口并显示图像?
我正在使用PIL库进行图像编辑。问题是,我不想每次将图像保存到硬盘上,再在资源管理器中查看。有没有一个简单的模块可以让我设置一个窗口并显示图像?
以下是来自PIL教程的开头:
一旦您拥有Image类的实例,您可以使用该类定义的方法来处理和操作图像。例如,让我们显示刚刚加载的图像:
>>> im.show()
更新:
现在,Image.show()
方法已经在Pillow fork of PIL中正式记录,并解释了它在不同操作系统上的实现方式。
im.show()
调用之前将图像格式属性显式设置为 .png(即 im.format = "PNG"
)。 - martineaushow()
方法是“脚本其他程序来显示图像”的最简单版本。(在早期的Windows系统中,您可能会得到一堆MSPaint窗口。)即使它无法正常工作,建议并尝试也是值得的。您实际上可以通过显式启动每个图像的MSPaint.exe来做类似且几乎同样简单的事情... - abarnertshow()
的问题。原文链接:http://support.microsoft.com/kb/2581947 下载链接:http://www.microsoft.com/en-us/downloaded/details.aspx?id=29219 - martineauim.show()
将使用与PIL创建的临时文件类型相关联的应用程序打开图像,因此如果这恰好是XnView,则可能会发生这种情况。许多应用程序会自动执行此操作(或在安装时询问您是否要执行此操作)。PIL的默认设置可能是为了避免需要安装第三方软件。 - martineau我测试过这个方法,对我来说可以正常工作:
from PIL import Image
im = Image.open('image.jpg')
im.show()
您可以使用pyplot显示图像:
from PIL import Image
import matplotlib.pyplot as plt
im = Image.open('image.jpg')
plt.imshow(im)
plt.show() # image will not be displayed without this
img.save("tmp.png") #Save the image to a PNG file called tmp.png.
对于MacOS:
import os
os.system("open tmp.png") #Will open in Preview.
对于大多数安装了X.Org和桌面环境的GNU/Linux系统:
import os
os.system("xdg-open tmp.png")
import os
os.system("powershell -c tmp.png")
您可以使用Tkinter,在不依赖于系统中已安装的图像查看器的情况下,在自己的窗口中显示图像:
import Tkinter as tk
from PIL import Image, ImageTk # Place this at the end (to avoid any conflicts/errors)
window = tk.Tk()
#window.geometry("500x500") # (optional)
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
对于Python 3,请用import tkinter as tk
替换import Tkinter as tk
。
roses = list(data_dir.glob('roses/*'))
abc = PIL.Image.open(str(roses[0]))
PIL.Image._show(abc)
是的,PIL.Image.Image.show()非常简单方便。
但如果您想将图像放在一起并进行比较,我建议您使用matplotlib。以下是一个示例:
import PIL
import PIL.IcoImagePlugin
import PIL.Image
import matplotlib.pyplot as plt
with PIL.Image.open("favicon.ico") as pil_img:
pil_img: PIL.IcoImagePlugin.IcoImageFile # You can omit. It helps IDE know what the object is, and then it will hint at the method very correctly.
out_img = pil_img.resize((48, 48), PIL.Image.ANTIALIAS)
plt.figure(figsize=(2, 1)) # 2 row and 1 column.
plt.subplots_adjust(hspace=1) # or you can try: plt.tight_layout()
plt.rc(('xtick', 'ytick'), color=(1, 1, 1, 0)) # set xtick, ytick to transparent
plt.subplot(2, 1, 1), plt.imshow(pil_img)
plt.subplot(2, 1, 2), plt.imshow(out_img)
plt.show()