Python Pillow - Image Blending



Image blending is a process of combining or mixing two images to create a new image. One common method for image blending is to use alpha blending. In alpha blending, each pixel in the result is computed based on a weighted sum of the corresponding pixels in the input images. The alpha channel, representing transparency, is used as the weight factor.

This technique is commonly used in graphics, image processing, and computer vision to achieve various visual effects.

The Python Pillow library provides the blend() function within its Image module to perform the blending operation on images.

The Image.blend() function

This function provides a convenient way to create a smooth transition between two images by specifying a blending factor (alpha). The function creates a new image by interpolating between two input images using a constant alpha value. The interpolation is performed according to the formula −

out=image1×(1.0−alpha)+image2×alpha

Following is the syntax of the function −

PIL.Image.blend(im1, im2, alpha)

Where −

  • im1 − The first image.

  • im2 − The second image. It must have the same mode and size as the first image.

  • alpha − The interpolation alpha factor. If alpha is 0.0, a copy of the first image is returned. If alpha is 1.0, a copy of the second image is returned. There are no restrictions on the alpha value. If necessary, the result is clipped to fit into the allowed output range.

Example

Let's see a basic example of blending two images using the Image.blend() method.

from PIL import Image

# Load two images
image1 = Image.open("Images/ColorDots.png")
image2 = Image.open("Images/pillow-logo-w.png")

# Blend the images with alpha = 0.5
result = Image.blend(image1, image2, alpha=0.5)

# Display the input and resultant iamges
image1.show()
image2.show()
result.show()

Input Images

color dots pillow logo

Output

resultant images

Example

Here is an example that demonstrates the use of PIL.Image.blend() with alpha values 2.

from PIL import Image

# Load two images
image1 = Image.open("Images/ColorDots.png")
image2 = Image.open("Images/pillow-logo-w.png")

# Blend the images with alpha = 2
result = Image.blend(image1, image2, alpha=2)

# Display the input and resultant iamges
image1.show()
image2.show()
result.show()

Input Images

color dots pillow logo

Output

image blend

Example

Here is an example that demonstrates the use of PIL.Image.blend() with alpha value 1.0. It will return a copy of the second image.

from PIL import Image

# Load two images
image1 = Image.open("Images/ColorDots.png")
image2 = Image.open("Images/pillow-logo-w.png")

# Blend the images with alpha = 2
result = Image.blend(image1, image2, alpha=1.0)

# Display the input and resultant iamges
image1.show()
image2.show()
result.show()

Input Images

color dots pillow logo

Output

pillow logo
Advertisements