This tutorial explains how to read an image in pillow
Before you’re actually able to begin using any of various Pillow image editing functions, you’ll have to first “read” or “load” the image into your Python program. This create a Pillow Image object, which can be further processed using it’s various methods.
Reading an Image in Pillow
In order to read an image, all we have to do is use the open()
function from the Image module in Pillow. However, there are certain circumstances in which the way we read images, can change.
File Path
If the image is in the same directory (same folder or location) as the python file, then you simply have to mention it’s name.
from PIL import Image
img = Image.open("kitten.jpg")
If however, the image is some where else, in a different directory, then you’ll have to specify the full file path.
img = Image.open("C://Users/CodersLegacy/Desktop/kitten.jpg")
This technique will work whether the Image is in the same directory, or not. The first method only works for one of the two cases however.
You’ll notice that we used double slashes in the file path, not a single “/”. The reason is that “/ is a special character, so you have to “escape” it using another “/”. Basically the first one indicates that the slash after it is actually a regular slash.
Extensions
While we normally include the extension of the image within the filename, we can actually leave it out. Pillow will attempt to read the image, and figure out the correct extension using it’s meta data.
img = Image.open("C://Users/CodersLegacy/Desktop/kitten")
Common image extensions are JPG, JPEG and PNG.
Exception handling
You may often run into errors related to missing images or incorrectly spelled file names. If you want to prevent your whole program from crashing due to a single error, you should use exception handling.
try:
img = Image.open("C://Users/Shado/Desktop/nonexistent_image.jpg")
except:
print("Image not found")
The above code will not crash if the image is not found, it will just print the error message and then move on.
Displaying the Image
Once you successfully read an image using Pillow, you can use the show()
function on it to display it using your default image viewer.
from PIL import Image
img = Image.open("C://Users/Shado/Desktop/kitten.jpg")
img.show()
There are many different things we can do once we have successfully read an image. Follow up on our other Pillow Tutorials to learn more!
This marks the end of the Python Pillow – Reading an Image Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.