Image Blending in Python with Pillow
Pillow - Image Blending
Blending refers to the process of combining two images together by taking a weighted average of their pixel values. The resulting image is a combination of the two images, with each contributing a certain amount of intensity to the final result.
To blend two images together in Python with Pillow library, you can use Image.blend() method.
In this tutorial, you will learn how to use Image.blend() to blend two given images using a specific alpha.
Steps to blend two images
The steps to blend two given images with Pillow are
- Import Image module from Pillow library.
- Read the two input images using Image.open() function, say
image1
andimage2
. - Resize the images to the same size using Image.resize() function.
- Convert the images to the same mode using Image.convert() function.
- Set an alpha (or weight) of each image, where the output pixel is calculated from the given images using
out = image1 * (1.0 - alpha) + image2 * alpha
. - Blend the two images using Image.blend() function:
Image.blend(image1, image2, alpha)
. The function returns blended image. - Save the blended image to required location using Image.save() function, or you may process the image further.
Resizing of images is necessary if the two images are of not same size. If the two images do not match in size, you will get an error message saying "images do not match".
Similarly, conversion of images to same mode is necessary if the two images are of not same mode.
Examples
1. Blend given two images
In the following example, we read two images: test_image.jpg
and test_image_house.jpg
, and blend these two images.
We save the resulting image to a file blended_image.jpg
.
Python Program
from PIL import Image
# Open the images to be blended
image1 = Image.open('test_image.jpg')
image2 = Image.open('test_image_house.jpg')
# Resize the images to the same size
image1 = image1.resize((800, 600))
image2 = image2.resize((800, 600))
# Convert images to same mode
image1 = image1.convert('RGB')
image2 = image2.convert('RGB')
# Define the weight of each image
alpha = 0.5
# Blend the images together
blended = Image.blend(image1, image2, alpha)
# Save the blended image
blended.save('blended_image.jpg')
Input Images
[test_image.jpg]
[test_image_house.jpg]
Output - Blended image [blended_image.jpg]
You may change the alpha and thus control the amount of an image from the two images that you would like in the resulting image.
Summary
In this Python Pillow Tutorial, we learned how to blend given two images using PIL.Image.blend() function, with the help of examples.