gpt4 book ai didi

python - 使用Python PIL库一张一张显示图像

转载 作者:太空宇宙 更新时间:2023-11-03 15:50:27 27 4
gpt4 key购买 nike

我打算使用Python PIL逐个显示目录中的图像列表(即在下一个图像窗口打开之前关闭上一个图像窗口)。这是我的代码,它似乎不起作用。它会依次打开图像,而不会关闭前一个窗口。

def show_images(directory):
for filename in os.listdir(directory):
path = directory + "/" + filename
im = Image.open(path)
im.show()
im.close()
time.sleep(5)

有人可以帮我解决这个问题吗?我坚持使用PIL库。谢谢

最佳答案

PIL.show() 调用外部程序来显示图像,将其存储在临时文件中后,可以是 GNOME 图像查看器,如果您使用 iPython 笔记本,甚至可以是内联 matplotlib。

据我从他们的文档中收集的信息PIL在这里,我发现执行此操作的唯一方法是通过 os.system() 调用或子进程调用执行 pkill

所以你可以将你的程序更改为如下所示:

import os
def show_images(directory):
for filename in os.listdir(directory):
path = directory + "/" + filename
im = Image.open(path)
im.show()
os.system('pkill eog') #if you use GNOME Viewer
im.close()
time.sleep(5)

如果您没有必要专门使用 PIL,您可以尝试切换到其他库(例如 matplotlib)进行显示,如此处所述 Matplotlib ,其中诸如plot.close()之类的简单调用将关闭图窗,而plot.clear()将清除图窗

import matplotlib.pyplot as plt

def show_images(directory):
for filename in os.listdir(directory):
path = directory + "/" + filename
im = Image.open(path)
plt.imshow(im)
plt.show()
plt.clf() #will make the plot window empty
im.close()
time.sleep(5)

关于python - 使用Python PIL库一张一张显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41357641/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com