Python Pillow – Read Image

Python – Read Image using Pillow

You can read an image in Python using using Image class of PIL library.

In this tutorial, we shall learn how to read or open an image using Pillow library, and different situations one might encounter, with the help of example programs.

Steps to Read an Image using PIL

To read an image with Python Pillow library, follow these steps.

  1. Import Image from PIL library.
  2. Use Image.open() method and pass the path to image file as argument. Image.open() returns an Image object. You can store this image object and apply image operations on it.

In this tutorial, we shall learn how to read or open an image using PIL package, with the help of example programs.

Examples

1. Read an image identified by path using PIL

In the following example, we shall read an image using Image.open() function of PIL package.

Python Program

from PIL import Image

im = Image.open("sample-image.png")
Copy

Image.open() returns object of class type PIL.PngImagePlugin.PngImageFile.

In this example, the image file is placed in the same location as that of the python example file. If you would like to read an image present at other location, you should provide the complete path.

In the following example program, we shall provide the complete path of the input image.

Python Program

from PIL import Image

im = Image.open("D:/images/sample-image.png")
Copy

2. Image not found – Negative scenario

In this example, we shall simulate a scenario, where we provide an invalid path to Image.open(). In other words the file does not exist at the path we provide.

Python Program

from PIL import Image

im = Image.open("D:/images/no-image.png")
Copy

As the image file is not present at the location, Image.open() throws FileNotFoundError.

Output

Traceback (most recent call last):
  File "d:/workspace/example.py", line 3, in <module>
    im = Image.open("D:/images/sample-image.png")
  File "C:\Users\pythonexamplesorg\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2652, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'D:/images/sample-image.png'

2. Read an image whose filename has no extension

In this example, we shall try to read an image with no extension. We are not specifying the extension of the image, if it is JPG, PNG, etc.

Python Program

from PIL import Image

im = Image.open("D:/sample")
Copy

Image.open() figures out the codec of the image using the data and meta data present in the contents of the image.

Summary

In this tutorial of Python Examples, we learned how to read an image using Python PIL library.

Related Tutorials

Code copied to clipboard successfully 👍