Display images one by one using Python PIL library

前端 未结 1 1084
我寻月下人不归
我寻月下人不归 2021-01-24 17:30

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

相关标签:
1条回答
  • 2021-01-24 17:53

    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)
提交回复
热议问题