Beginner Guide to Python Extract Different Region of Two Images with Pillow – Python Pillow Tutorial

By | August 30, 2020

In this tutorial, we will focus on how to extract different region of two images by python pillow package, which is very useful when you are processing images.


We first import pillow package in python script.

from PIL import Image, ImageChops

Load two images data with pillow

In this example, we will extract different region of two images. In order to do this, we should load these two images data by python pillow.

im1 =" test image 1.png", mode='r')
im2 =" test image 2.png", mode='r')

Here, im1 and im2 contains two image data.

They are:

im1 im2 test image 1 test image 2

Get different region of two images

diff = ImageChops.difference(im1, im2)

In this example, we will use ImageChops class to get the different region.

Extract the different region from images

box = diff.getbbox()
img1_diff = im1.crop(box)
img2_diff = im2.crop(box)

img1_diff is a pillow image, which contains different region in im1 comparing to im2. img2_diff contains different region in im2 comparing to im1.

Save image to file

After extracting different region from images, we then save them to files. Here is an example code:"img1_diff.jpeg")"img2_diff.jpeg")

Run this python script code, you will get result like:

img1_diff img2_diff
different image region in image 1 different image region in image 2

From the result we can find we extract different region from two images successfully.

Leave a Reply

Your email address will not be published. Required fields are marked *