Image Overlaying in Python with Pillow
Pillow - Image Overlaying
Overlaying is the process of placing one image on top of another.
To overlay an image over a base image in Python with Pillow library, you can use Image.paste() method.
In this tutorial, you will learn how to use Image.paste() to over an image over another.
Steps to overlay image
The steps to overlay an image over another image with Pillow are
- Import Image module from Pillow library.
- Read the two input images using Image.open() function, say
base_img
andoverlay_img
. - Convert the overlay image to RGBA mode using Image.convert() function.
- Define the position where the overlay image will be pasted on the base image. This must be a tuple of (x position, y position).
- Overlay the image over base image using Image.paste() method. The base image object is modified with the resulting image.
- Save the base image to required location using Image.save() function.
Examples
1. Overlay an image on given image
In the following example, we read two images: test_image.jpg
and test_image_house.jpg
, and overlay the second image on the first image.
We save the resulting image to a file overlayed_image.jpg
.
Python Program
from PIL import Image
# Open the base and overlay images
base_img = Image.open('test_image.jpg')
overlay_img = Image.open('test_image_house.jpg')
# Convert the overlay image to RGBA mode
overlay_img = overlay_img.convert('RGBA')
# Define the position where the overlay image will be pasted
position = (200, 100)
# Overlay the image over base image
base_img.paste(overlay_img, position, overlay_img)
# Save the resulting image
base_img.save('overlayed_image.jpg')
Input Images
base_img
overlay_img
overlayed_image.jpg
You may change the position, or change the size of the overlay image to get the desired results.
Summary
In this Python Pillow Tutorial, we learned how to overlay an image on a base image using PIL.Image.paste() function, with the help of examples.