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
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 cv2import 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 imagesimage1 = 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
Where:
alphais the weight of the first image (between 0 and 1).betais the weight of the second image (also between 0 and 1).gammais 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 blendingalpha = 0.5beta = 0.5gamma = 0# Perform image blendingblended_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 weightsalpha = 0.3beta = 0.7gamma = 0# Perform custom image blendingcustom_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()Code explanation
Let's go through the code line by line, explaining each part:
Lines 5–6: Loading the images. We use the
cv2.imread()function to read the images"image1.jpg"and"image2.jpg", and store them inimage1andimage2variables, 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 resizeimage2to the same size asimage1. We provide the new size as(image1.shape[1], image1.shape[0]), which is the width and height ofimage1.Lines 12–14: Defining blending weights. We define three variables
alpha,beta, andgamma, which are used in thecv2.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 blendimage1andimage2using the blending weights defined earlier (alpha,beta, andgamma). The resulting blended image is stored in theblended_imagevariable.Lines 20–22: Defining custom blending weights. We define three variables
alpha_custom,beta_custom, andgamma_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 blendimage1andimage2, but this time using the custom blending weights defined earlier (alpha_custom,beta_custom, andgamma_custom). The resulting custom blended image is stored in thecustom_blended_imagevariable.Lines 28–31: 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 bymatplotlib. We use thecv2.cvtColor()function with thecv2.COLOR_BGR2RGBconversion 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. The1specifies the number of rows,4specifies the number of columns, andfigsizedefines the size of the overall figure.Lines 37–52: Displaying the images in subplots. We use the subplots'
axesarray to access each individual subplot. For each subplot, we use theimshow()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.
Free Resources