A lot of applications use digital images, and with this there is usually a need to process the images used. If you are building your application with Python and need to add image processing features to it, there are various libraries you could use. Some popular ones are OpenCV, scikit-image, Python Imaging Library and Pillow.
We won’t debate on which library is the best here, they all have their merits. This article will focus on Pillow, a library that is powerful, provides a wide array of image processing features, and is simple to use.
Pillow is a fork of the Python Imaging Library (PIL). PIL is a library that offers several standard procedures for manipulating images. It’s a powerful library, but hasn’t been updated since 2011 and doesn’t support Python 3. Pillow builds on this, adding more features and support for Python 3. It supports a range of image file formats such as PNG, JPEG, PPM, GIF, TIFF and BMP. We’ll see how to perform various operations on images such as cropping, resizing, adding text to images, rotating, greyscaling, e.t.c using this library.
Installation and Project Setup
Before installing Pillow, there are some prerequisites that must be satisfied. These vary for different operating systems. We won’t list the different options here, you can find the prerequisites for your particular OS in this installation guide.
After installing the prerequisite libraries, you can install Pillow with `pip:
$ pip install Pillow
To follow along, you can download the images (coutesy of Unsplash) that we’ll use in the article. You can also use your own images.
All examples will assume the required images are in the same directory as the python script file being run.
The Image Object
A crucial class in the Python Imaging Library is the
Image class. It is defined in the
Image module and provides a PIL image on which manipulation operations can be carried out. An instance of this class can be created in several ways: by loading images from a file, creating images from scratch or as a result of processing other images. We’ll see all these in use.
To load an image from a file, we use the
open() function in the
Image module passing it the path to the image.
from PIL import Image
image = Image.open('unsplash_01.jpg')
If successful, the above returns an
Image object. If there was a problem opening the file, an
IOError exception will be raised.
After obtaining an
Image object, you can now use the methods and attributes defined by the class to process and manipulate it. Let’s start by displaying the image. You can do this by calling the
show() method on it. This displays the image on an external viewer (usually xv on Unix, and the Paint program on Windows).
You can get some details about the image using the object’s attributes.