What is image blending OpenCV?

Image blending is a popular technique in computer vision and image processing that allows us to combine two or more images to create a seamless and visually appealing result. This technique finds its applications in various areas, such as creating panoramas, special effects in movies, and more.

In this Answer, we will explore how to blend two images using OpenCV, a powerful library for computer vision tasks.

Getting started

To follow along with this tutorial, we need to have Python and OpenCV installed on our system. We can install OpenCV using pip:

pip install opencv-python
Command to install OpenCV

Also, we have to ensure that the images we want to blend are available on our system. Now, let's proceed with the steps to blend the images.

1. Import necessary libraries

import cv2
import matplotlib.pyplot as plt

In this step, we import the necessary libraries for the program. OpenCV (cv2) is used for image processing and matplotlib.pyplot for image display.

2. Loading the images

Let's start by loading the two images we want to blend. For this example, we'll call them "image1.jpg" and "image2.jpg".

# Load the images
image1 = cv2.imread("image1.jpg")
image2 = cv2.imread("image2.jpg")

3. Image blending

To blend the two images, we will use the addWeighted() function in OpenCV. This function calculates the weighted sum of two images, allowing us to control the intensity of each image in the final blend.

The formula for blending two images can be expressed as:

output_image = (image1 * alpha) + (image2 * beta) + gamma
Formula for blending two images

Where:

  • alpha is the weight of the first image (between 0 and 1).

  • beta is the weight of the second image (also between 0 and 1).

  • gamma is the Scalar added to each pixel.

Let's blend the two images with equal weights (0.5 for both images) and no scalar addition:

# Define the weights for blending
alpha = 0.5
beta = 0.5
gamma = 0
# Perform image blending
blended_image = cv2.addWeighted(image1, alpha, image2, beta, gamma)

4. Custom blending

We can experiment with different blending weights to achieve different effects. For example, to give more prominence to one image over the other, we can adjust the alpha and beta values accordingly. Keep in mind that the sum of alpha and beta should not exceed 1.

# Define custom blending weights
alpha = 0.3
beta = 0.7
gamma = 0
# Perform custom image blending
custom_blended_image = cv2.addWeighted(image1, alpha, image2, beta, gamma)

Let's run the following widget to see how image blending works using OpenCV.

import cv2
import matplotlib.pyplot as plt

# Load the images
image1 = cv2.imread("image1.jpg")
image2 = cv2.imread("image2.jpg")

# Resize one image to match the size of the other
image2 = cv2.resize(image2, (image1.shape[1], image1.shape[0]))

# Define the weights for blending
alpha = 0.5
beta = 0.5
gamma = 0

# Perform image blending
blended_image = cv2.addWeighted(image1, alpha, image2, beta, gamma)

# Define custom blending weights
alpha_custom = 0.3
beta_custom = 0.7
gamma_custom = 0

# Perform custom image blending
custom_blended_image = cv2.addWeighted(image1, alpha_custom, image2, beta_custom, gamma_custom)

# Convert BGR images to RGB for displaying with matplotlib
image1_rgb = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
image2_rgb = cv2.cvtColor(image2, cv2.COLOR_BGR2RGB)
blended_image_rgb = cv2.cvtColor(blended_image, cv2.COLOR_BGR2RGB)
custom_blended_image_rgb = cv2.cvtColor(custom_blended_image, cv2.COLOR_BGR2RGB)

# Create a figure with subplots to display the images
fig, axes = plt.subplots(1, 4, figsize=(16, 4))

# Display the original images
axes[0].imshow(image1_rgb)
axes[0].set_title("Image 1")
axes[0].axis('off')

axes[1].imshow(image2_rgb)
axes[1].set_title("Image 2")
axes[1].axis('off')

# Display the blended images
axes[2].imshow(blended_image_rgb)
axes[2].set_title("Blended Image")
axes[2].axis('off')

axes[3].imshow(custom_blended_image_rgb)
axes[3].set_title("Custom Blended Image")
axes[3].axis('off')

# Show the plot
plt.show()
Complete code of image blending in OpenCV

Code explanation

Let's go through the code line by line, explaining each part:

  • Lines 56: Loading the images. We use the cv2.imread() function to read the images "image1.jpg" and "image2.jpg", and store them in image1 and image2 variables, respectively. The images are loaded as NumPy arrays in the BGR color format.

  • Line 9: Resizing the second image. Since the two images need to have the same dimensions for blending, we use the cv2.resize() function to resize image2 to the same size as image1. We provide the new size as (image1.shape[1], image1.shape[0]), which is the width and height of image1.

  • Lines 1214: Defining blending weights. We define three variables alpha, beta, and gamma, which are used in the cv2.addWeighted() function for blending the images. These values control the intensity of each image in the final blend.

  • Line 17: Blending the images. We use the cv2.addWeighted() function to blend image1 and image2 using the blending weights defined earlier (alpha, beta, and gamma). The resulting blended image is stored in the blended_image variable.

  • Lines 2022: Defining custom blending weights. We define three variables alpha_custom, beta_custom, and gamma_custom, which will be used for a custom blending operation later.

  • Line 25: Performing custom image blending. Similar to the previous blending operation, we use the cv2.addWeighted() function to blend image1 and image2, but this time using the custom blending weights defined earlier (alpha_custom, beta_custom, and gamma_custom). The resulting custom blended image is stored in the custom_blended_image variable.

  • Lines 2831: Converting BGR images to RGB format. Before displaying the images with matplotlib, we need to convert the images from the BGR color format used by OpenCV to the RGB color format used by matplotlib. We use the cv2.cvtColor() function with the cv2.COLOR_BGR2RGB conversion code for each of the images.

  • Line 34: Creating a figure with subplots. We create a single row of four subplots using plt.subplots() function. The 1 specifies the number of rows, 4 specifies the number of columns, and figsize defines the size of the overall figure.

  • Lines 3752: Displaying the images in subplots. We use the subplots' axes array to access each individual subplot. For each subplot, we use the imshow() function to display the corresponding image. We also set the titles and turn off the axes ticks for a cleaner display.

  • Line 55: Showing the plot. Finally, we use plt.show() to display the entire figure containing the subplots with the original images and the blended images.

Wrapping up

Image blending is a powerful technique that can be used to create stunning visual effects and composite images. Feel free to experiment with different blending weights to enhance your projects further.

Copyright ©2024 Educative, Inc. All rights reserved