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!
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!
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()
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()