Working with image files is a common task in data analysis. In Python, handling image data is made convenient using libraries like PIL (Python Imaging Library).
One common image file format you might encounter is PNG (Portable Network Graphics). In this tutorial, we will learn how to load a PNG file in Python with the help of the PIL/Pillow library.
Step 1: Installation of PIL/Pillow
First of all, you need to have the PIL (or its fork, Pillow) library installed in your Python environment. It is not part of the Python standard library. You can install it using pip:
1 |
pip install pillow |
Step 2: Importing Necessary Library
Once Pillow is installed, we can now utilize it by importing the Image module:
1 |
from PIL import Image |
Step 3: Loading the PNG Image
To load an image, we use the Image.open() method, passing the image filename:
1 |
img = Image.open('example.png') |
With this line of code, Python opens the image file ‘example.png’ in the current directory and assigns it to the variable ‘img’.
Step 4: Verifying the Image Loading
To verify whether the image loading was successful or not, you can display the image in a default viewer:
1 |
img.show() |
Step 5: Accessing Image Properties
After loading the image, we may want to access its properties, like its size (width and height) and mode (number of color channels):
1 2 |
print(img.size) print(img.mode) |
All these steps look as follows:
Full code:
1 2 3 4 5 6 7 |
from PIL import Image img = Image.open('example.png') img.show() print(img.size) print(img.mode) |
Output:
(496, 331) RGB
The size is a tuple that represents the width and height of the image in pixels. The mode ‘RGB’ indicates an image with three color channels: Red, Green, and Blue.
Conclusion
That’s it! We’ve just loaded a PNG image using Python and the Pillow library. As we’ve seen, it’s a straightforward task with just a few lines of code. From here, you can manipulate the image data for your specific needs, such as image analysis, manipulation, or machine learning tasks.