How to Load All Images from a Folder in Python

In the realm of image processing and computer vision, a common task is to load multiple images from a directory for further processing or analysis. This could be for tasks such as image classification, object detection, or simply for applying various image transformations. Python, with its rich ecosystem of libraries, makes this task straightforward, especially when using libraries like OpenCV. In this post, we'll dive into how to efficiently load all images from a specified folder.

Getting Started

Before we begin, ensure you have the necessary library installed. We'll be using OpenCV, a powerful library for image processing tasks. If you haven't installed it yet, you can do so by running the following command in your terminal or command prompt:

pip install opencv-python

The Approach

The process of loading all images from a folder involves two main steps:

  1. Listing all the files in the folder.
  2. Loading each file as an image.

Listing Files in a Folder

Python's os module allows us to interact with the file system, and we can use the os.listdir() function to list all files in a directory. However, to ensure we're only dealing with image files, we might want to filter the list by file extensions (e.g., .jpg, .png).

Loading Images

Once we have the list of image files, we can load each one using OpenCV's cv2.imread() function. This function reads an image from a file and returns it as a NumPy array. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix.

Putting It All Together

Let's combine these steps into a complete example:

import os
import cv2

def load_images_from_folder(folder):
    images = []
    for filename in os.listdir(folder):
        # Check for file extension
        if filename.endswith(('.png', '.jpg', '.jpeg')):
            img = cv2.imread(os.path.join(folder, filename))
            if img is not None:
                images.append(img)
    return images

folder_path = 'path/to/your/images'
images = load_images_from_folder(folder_path)

print(f"Loaded {len(images)} images from {folder_path}")

This script defines a function load_images_from_folder that takes a folder path as input and returns a list of images. It first lists all files in the specified folder, then filters out non-image files based on their extensions, and finally loads each image file into a list.

Conclusion

Loading all images from a folder is a common task that can be efficiently handled using Python and OpenCV. The approach outlined above is straightforward and can be easily integrated into larger image processing or computer vision projects. Remember, while this example uses specific file extensions (.png, .jpg, .jpeg), you can modify the code to include any other image formats supported by OpenCV. Happy coding!