Kalebu Jordan

Become a Pro Python Developer

Hi guys,

In this article, I will walk you through how you can get started doing image processing tasks using python imagining library(PIL) commonly known as a pillow.

what is pillow ?

Pillow is Python Imaging Library that is free and open-source an additional library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats.

Let’s get started

The Image class

The most important class in the Python Imaging Library is the Image class, through this class we are able to load various formats of the image in a way that it can be easily processed.

Loading image from file

We use the open ( ) method to load an image from a file by specifying the path to our image.

>>> from PIL import Image
>>> sample = Image.open('sample.jpg')

You can try checking the type of sample after you have loaded an image

>>> type(sample)
<class 'PIL.JpegImagePlugin.JpegImageFile'>

You can view your image property such as format, size, and mode as shown below.

>>> sample.format
>>> sample.size
(250, 283)
>>> sample.mode

Also, you preview the loaded image using show ( ) as shown below

>>> sample.show()

Output :

Image Format Conversion

Once you open your image with Pillow in one format you can save it again in another image format like from jpg to png and much more.

For Instance let’s try to write a Simple Python program to convert all images on your project directory which are in jpg format to png format.

Note :
When opening your image fails the Pillow library throws IOError exception , there you should consider using that exception on your Program.


import os
import sys
from PIL import Image

jpg_images = [image for image in os.listdir() if image.endswith('.jpg')]

for jpg_image in jpg_images:
        new_name = jpg_image.split('.')[0] + '.png'
    except IOError as error:
        print('Couldn\'t read {} '.format(jpg_image))

Once you run the above image on directory with jpg images , it will open all of them and convert into png . same wise you can do to convert other format .

Image Cropping

Pillow can also be used to perform image cropping where by you can extract a sub rectangle of a given image by specifying coordinates of the sub rectangle.

Therefore before you perform cropping you need to first show the image to the screen and then observe the dimension and then pick the coordinate point of are you want to crop.

Example of usage:

>>> from PIL import Image
>>> picture = Image.open('sample.png')
>>> cord = (50, 50, 300, 300)
>>> new_picture = picture.crop(cord)
>>> new_picture.show()


As we can see the image have been successful cropped. The coordinates of the surface to be cropped are represented by diagonal point.

Whereby first two point are (x, y) form the upper left diagonal point and next two point (x2, y2) are also diagonal point from the bottom right.

Geometrical Transformation

With Pillow we can perform some geometrical transformation on our image include resizing image size and rotations .

This knowledge play a great role when generating data for deep learning by transforming one image to form other tons of image in different angles.

Image resizing
>>> from PIL import Image
>>> image = Image.open('sample.png')
>>> resized_image = image.resize((200, 200))
>>> resized_image.save('resized.png')

When you run the above code you should see a new resized image on you local directory with dimension of 200 x 200.

Image Rotation
>>> from PIL import Image
>>> image = Image.open('sample.png')
>>> rotated_img = image.rotate(80)
>>> rotated_img.save('rotated_img.png')

Use rotation feature to generate 360 images of the same picture at different angles , doing this way will help us generate as many as data for your deep learning model .


from PIL import Image 

images = ['sample.jpg']

for img in images:
        org_img = Image.open(img)
        for angle in range(1, 361):
            image_name = str(angle)+'.jpg'
            new_img = org_img.rotate(angle)
    except IOError:
        print('Couldn\'t read {}'.format(img))

After running the above script , you should see 360 images of the same original image at different angles as shown below.

Image Filtering

Filtering is a technique for modifying or enhancing an image. For example, you can filter an image to emphasize certain features or remove other features. 

Image filtering is useful for many applications, including smoothing, sharpening, removing noise, and edge detection.

There many filters available on Pillow Library including BLUR , BoxBlur , CONTOUR, FIND_EDGES , Filter , GaussianBlur , Kernel , MaxFilter , MedianFilter , SHARPEN , SMOOTH and etc.

Example of Usage.

Let’s try finding edges in the below picture using FIND_EDGES filter.

>>> from PIL import Image
>>> from PIL import Image, ImageFilter
>>> image = Image.open('brain.jpeg')
>>> edges = image.filter(ImageFilter.FIND_EDGES)
>>> edges.show()

Output :

Same wise you can experiments with different filters in Python depending on what you’re trying to do.

Reading Image From open file

Also you can use pillow to read an Image from Python file object as shown below :

>>> from PIL import Image
>>> image = Image.open(open('brain.jpeg', 'rb'))

Reading Image from URL

On this you will have to use Pillow in combination with requests, requests will have to send a get requests to the server to get the raw bytes of image and the pillow will read those bytes.

>>> import requests
>>> from PIL import Image
>>> url = 'https://i1.wp.com/kalebujordan.com/wp-content/uploads/2020/04/code-1084923.png'
>>> raw = requests.get(url, stream=True).raw
>>> Image.open(raw).show()

Output :

Creating new Images

With Pillow you can also create new blank image , of you might need in variety of purpose . use Image.new ( ) to generate entirely new image .

Syntax :

new = Image.new(mode, shape, color)

Example of Usage :

>>> from PIL import Image
>>> new_img = Image.new('RGB', (500, 500), 'blue')
>>> new_img.show()

Output :

Drawing Rectangle on Images

Pillow can also be used to draw Rectangle on Images, this commonly applied on object detection where by you can draw rectangular box over detected object .

Example of Usage :

Let’s try drawing a rectangular box inside a blank image

>>> from PIL import Image, ImageDraw
>>> new_img = Image.new('RGB', (400, 400), 'black')
>>> pencil = ImageDraw.Draw(new_img)
>>> pencil.rectangle((200, 50, 300, 300), fill ='green')
>>> new_img.show()

Output :

The first two coordinates represent (x ,y ) of the left upper diagonal and the next two (x2, y2) represent the coordinate point of the bottom right .

Drawing Text on Images

We can also use Pillow Library to draw Text on Images

>>> from PIL import Image , ImageDraw, ImageFont 
>>> new_img = Image.new('RGB', (200, 200), 'black')
>>> font = ImageFont.load_default()
>>> pencil = ImageDraw.Draw(new_img)
>>> pencil.text((100,100),'Hello World',  font=font, fill='blue')
>>> new_img.show()

Output :

Hope you find this post interesting , don’t forget to subscribe to get more tutorials like this.

I also recommend you checking this ;

In case of any suggestion or comment , drop it on the comment box and I will reply to you immediately.

One thought on “Getting started with image processing using a pillow – Python

Leave a Reply


Enjoy this blog? Please spread the word :)