深度阅读

How to iterate through images in a folder Python?

作者
作者
2023年08月22日
更新时间
10.68 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。