使用Python PIL库一一显示图像 [英] Display images one by one using Python PIL library

查看:152
本文介绍了使用Python PIL库一一显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I intend to show a list of images in a directory one by one using Python PIL(i.e close the previous image window before the next image window opens). Here is my code which doesn't seem to work . It opens images one after the other without closing the previous window.

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库. 谢谢

Can anyone help me with this? I insist on using the PIL library. Thanks

推荐答案

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

PIL.show() calls an external program to display the image, after storing it in a temporary file, could be the GNOME image viewer or even the inline matplotlib if you use iPython notebook.

根据我从他们的文档中收集的信息 PIL 在这里,我看到做到这一点的唯一方法是通过os.system()调用或子进程调用进行pkill.

From what I gather from their documentation PIL here, I see that the only way to do this is, to do a pkill through a os.system() call or a subprocess call.

因此您可以将程序更改为以下内容:

So you could change your program to something like this :

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)进行显示,如此处

If you don't have a necessity to use PIL exclusively, you can try switching to other libraries such as matplotlib for showing, as described here Matplotlib, where a simple call such as plot.close() will close the figure, and plot.clear() will clear the figure

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 PIL库一一显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆