Lunchtime #5: Pillow¶

Why using Python for image processing?¶

  • Easy automation of image processing (compared to GUIs)
  • High-Level interfaces usable without very deep knowledge of image formats
  • Easy integration with other Python-based tools for e.g.
    • Image Analysis
    • Web Scraping
    • ML/AI

Pillow is the friendly fork of PIL, the Python Imaging Library:¶

  • PIL is/was the state-of-the-art library for image processing in Python
  • Had several issues caused by the project maintenance:
    • Compatibility issues with standard installation procedures
    • Missing open community work for issues, contributions etc.
    • Sustainability issues due to missing Continuous Integration
  • Pillow has stepped in, PIL had its last release in 2009

The Basics: Loading an image¶

We import Image from the PIL package:

In [1]:
from PIL import Image

We can open an image from disk by using open:

In [2]:
if "google.colab" in str(get_ipython()):
    !wget https://ssciwr.github.io/lunch-time-python/lunchtime5/thingstaette.png -q
img = Image.open("thingstaette.png")

The image is represented using the Image class from PIL (or one of its specialized subclasses). Images can be created by loading from file, from other images or programmatically.

The img object can be queried for a number of metadata fields of the image:

In [3]:
img.format
Out[3]:
'PNG'
In [4]:
img.size
Out[4]:
(856, 652)
In [5]:
img.width, img.height
Out[5]:
(856, 652)
In [6]:
img.mode
Out[6]:
'RGBA'
In [7]:
img.getbands()
Out[7]:
('R', 'G', 'B', 'A')

Visualizing images in Jupyter¶

To display the image directly in Jupyter notebooks, we can use the IPython's rich display system. Alternatively, img.show() can open the image in an external viewer.

In [8]:
img
Out[8]: