Working with images is quite common in various applications, such as image recognition, image processing, and computer graphics. This tutorial will help you to learn how to read images from a list using Python’s Pillow library.
To get started, make sure to install the Pillow library, which stands for “Python Imaging Library (Fork).”
1 |
pip install Pillow |
Now, let’s learn how to read images from a list in Python.
Step 1: Import the necessary libraries
Here, we will be using the Image module from the PIL (Pillow) library.
1 |
from PIL import Image |
Step 2: Create the list of image filenames
Prepare a list of filenames or paths of images that you want to read. For this tutorial, let’s assume you have three images named “image1.jpg”, “image2.jpg”, and “image3.jpg”.
1 |
image_list = ["image1.jpg", "image2.jpg", "image3.jpg"] |
Step 3: Read images from the list
Using a loop, you can create a list of Image objects. These objects can be later displayed or processed as per your needs.
1 2 3 4 5 6 7 8 |
images = [] for img_file in image_list: try: img = Image.open(img_file) images.append(img) except IOError as e: print(f"Error reading image {img_file}: {e}") |
This opens and appends each image using the Image module from the PIL library. If the image cannot be opened or read, it will display an error message with the filename and the exception details.
1 2 3 4 5 6 7 8 9 10 11 12 |
from PIL import Image image_list = ["image1.jpg", "image2.jpg", "image3.jpg"] images = [] for img_file in image_list: try: img = Image.open(img_file) images.append(img) except IOError as e: print(f"Error reading image {img_file}: {e}") |
Output
Error reading image image1.jpg: [Errno 2] No such file or directory: 'image1.jpg' Error reading image image2.jpg: [Errno 2] No such file or directory: 'image2.jpg' Error reading image image3.jpg: [Errno 2] No such file or directory: 'image3.jpg'
As shown in the output above, we don’t have those image files in the current directory. Replace the filenames with your actual image files for your application.
Conclusion
In this tutorial, you learned how to read images from a list of filenames using Python and the Pillow library. After reading the images, you can process/display them depending on your requirements.
Now you have a starting point to build your image processing or recognition application by accessing multiple images using Python.