How to iterate through images in a folder Python?

Published on Aug. 22, 2023, 12:15 p.m.

To iterate through images in a folder in Python, you can use the os and PIL libraries. Here’s an example:

import os
from PIL import Image

directory = "path/to/directory"  # specify the directory containing your images
for file in os.listdir(directory):
    if file.endswith(".jpg") or file.endswith(".png"):  # adjust file extensions as needed
        image_path = os.path.join(directory, file)
        with Image.open(image_path) as img:
            # do something with the image, such as display it or process it

In this code, we use the os library to iterate over all files in the specified directory. We then check the file extension to ensure that it’s a valid image file, and use the PIL library to open the image as an Image object. You can then use the image object to display the image or perform any other required processing.

Note that your specific requirements may require some modifications to this base code, such as using a different image processing library or changing the specific processing steps performed on each image.

Tags: