Last modified: Jan 17, 2025 By Alexander Williams

Python OpenCV cv2.addWeighted() Guide

Blending images is a common task in image processing. OpenCV provides the cv2.addWeighted() function to blend two images seamlessly. This guide will explain how to use it effectively.

What is cv2.addWeighted()?

The cv2.addWeighted() function is used to blend two images by applying a weighted sum. It combines the pixel values of two images with specified weights and a gamma value.

The syntax is simple:


cv2.addWeighted(src1, alpha, src2, beta, gamma)

src1 and src2 are the input images. alpha and beta are the weights for each image. gamma is a scalar added to the sum.

How Does cv2.addWeighted() Work?

The function calculates the weighted sum of the two images using the formula:

dst = src1 * alpha + src2 * beta + gamma

This formula ensures that the output image is a blend of the two input images. The weights control the contribution of each image to the final result.

Example: Blending Two Images

Let's blend two images using cv2.addWeighted(). Below is an example code:


import cv2

# Load two images
image1 = cv2.imread('image1.jpg')
image2 = cv2.imread('image2.jpg')

# Ensure both images have the same dimensions
image2 = cv2.resize(image2, (image1.shape[1], image1.shape[0]))

# Blend the images
blended_image = cv2.addWeighted(image1, 0.7, image2, 0.3, 0)

# Display the result
cv2.imshow('Blended Image', blended_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

In this example, image1 contributes 70% to the final image, while image2 contributes 30%. The gamma value is set to 0.

Practical Applications

cv2.addWeighted() is widely used in image processing tasks. It is useful for creating overlays, blending textures, and combining images for visual effects.

For example, you can use it to create a watermark effect by blending a logo with an image. It is also used in image merging and splitting operations.

Tips for Using cv2.addWeighted()

Ensure that both images have the same dimensions. If not, resize one image to match the other. Also, experiment with different weights to achieve the desired blend.

For more advanced transformations, consider using cv2.getRotationMatrix2D() or cv2.warpPerspective().

Conclusion

cv2.addWeighted() is a powerful tool for blending images in OpenCV. It is easy to use and offers flexibility in controlling the contribution of each image. With this guide, you can start blending images like a pro.