使用Python PIL库逐个显示图像

时间:2016-12-28 07:47:50

标签: python python-imaging-library

我打算使用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库。 谢谢

1 个答案:

答案 0 :(得分:0)

PIL.show()调用外部程序显示图像,将其存储在临时文件中后,如果使用iPython笔记本,可以是GNOME图像查看器,甚至是内联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)
相关问题