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)

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

Thanks

解决方案

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.

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)

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值