This Python script demonstrates how to blend multiple images using the Pillow (PIL) library.
It opens three images, resizes them to the same dimensions, and then overlays them onto a blank canvas. The blending is achieved using the paste method with transparency masks, allowing the images to merge smoothly.
Finally, the script saves and displays the blended result. This technique is useful for creating artistic compositions, overlays, or image processing applications.
from PIL import Image
# Open the images to blend
image1 = Image.open("image1.jpg")
image2 = Image.open("image2.jpg")
image3 = Image.open("image3.jpg")
# Resize images to the same dimensions
width, height = 800, 600
image1 = image1.resize((width, height))
image2 = image2.resize((width, height))
image3 = image3.resize((width, height))
# Create a blank image to blend the images onto
blend_image = Image.new("RGB", (width, height), "white")
# Blend images onto the blank image
blend_image.paste(image1, (0, 0))
blend_image.paste(image2, (0, 0), mask=image2)
blend_image.paste(image3, (0, 0), mask=image3)
# Save the blended image
blend_image.save("blended_image.jpg")
# Display the blended image
blend_image.show()
from PIL import Image
: Imports the Image module from the Pillow library, which is used for working with images.image1
, image2
, image3
: Opens three images (image1.jpg
, image2.jpg
, image3.jpg
) to blend together.width, height = 800, 600
: Defines the desired width and height for the resized images.image1.resize((width, height))
, image2.resize((width, height))
, image3.resize((width, height))
: Resizes each image to the specified dimensions to ensure they are compatible for blending.blend_image = Image.new("RGB", (width, height), "white")
: Creates a new blank image (blend_image
) with the specified dimensions and white background.blend_image.paste(image1, (0, 0))
: Pastes image1
onto the blank image at the top-left corner.blend_image.paste(image2, (0, 0), mask=image2)
: Pastes image2
onto the blank image, using image2
as a mask for transparency.blend_image.paste(image3, (0, 0), mask=image3)
: Pastes image3
onto the blank image, using image3
as a mask for transparency.blend_image.save("blended_image.jpg")
: Saves the blended image as blended_image.jpg
.blend_image.show()
: Displays the blended image using the default image viewer.This code example demonstrates the process of blending multiple images together using the Pillow library, including resizing, blending, and saving the composite image.
The output of the above code example is a new image file named “blended_image.jpg” containing a composite image created by blending the three input images (image1.jpg
, image2.jpg
, image3.jpg
). This composite image will be displayed on your screen if your environment supports image viewing when the blend_image.show()
method is called.
The blended image will have the following characteristics: