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.
Preliminary
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 = Image.open("tutorialexample.com test image 1.png", mode='r') im2 = Image.open("tutorialexample.com test image 2.png", mode='r')
Here, im1 and im2 contains two image data.
They are:
im1 | im2 |
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.save("img1_diff.jpeg") img2_diff.save("img2_diff.jpeg")
Run this python script code, you will get result like:
img1_diff | img2_diff |
From the result we can find we extract different region from two images successfully.