0

I would like to show the first 5 pictures from a folder, consisting of .png pictures. How can I do that, without calling them one by one via their name in python?

Thanks!

  • Does this answer your question? [Display an image with Python](https://stackoverflow.com/questions/35286540/display-an-image-with-python) – Ahmet Dundar Sep 30 '21 at 15:45

2 Answers2

0
import os
from PIL import Image


for subdir, dirs, files in os.walk("directory path"):
    for file in files:
        if file.lower().endswith(".png"):
           image = Image.open(os.path.join(subdir,file)
           image.show()

I think that should do it. May need to do image.close() after image.show()

0

You can use the package os to list file in a directory. Then you filter the results to keep the files with the correct extention. You take the 5 first elements of the list. Finaly you use matplotlib.image to load the image and matplotlib.pyplot to plot the image.

import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

filenames = os.listdir()
filenames = list(filter(lambda x: x.endswith('.png'), filenames))
filenames = filenames[:5]

for f in filenames:
    plt.imshow(mpimg.imread(f))
    plt.show()
amarion
  • 353
  • 3
  • 10