【问题标题】:Display images one by one using Python PIL library使用 Python PIL 库一张一张显示图像
【发布时间】:2023-09-28 19:59:01
【问题描述】:

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

【问题讨论】:

  • 如果库对您来说不是问题,那么您可以尝试 'cv2' 库,您可以在其中使用 cv2.waitKey(0) 连续播种图像。
  • PIL 调用外部查看器程序来显示图像。你用的是哪一个?可能是displayxv;这些在您的系统和您的 PATH 中可用吗?
  • PIL 的.show 方法只是一个方便的功能,允许开发人员在编写代码时查看图像,它不打算用于向用户显示图像。如果您的程序需要控制图像显示,您应该使用 GUI 框架。这在 Tkinter 中很容易做到。

标签: python python-imaging-library


【解决方案1】:

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)

【讨论】:

  • 这似乎不起作用,它只是启动一个新的图像窗口而不杀死前一个。
  • 你可以尝试使用 matplotlib 来显示图像吗?现在将为此编辑并添加一个新的 sn-p。