Thursday, October 26, 2023

OpenCV and Image Processing - Blend Image

Blending images refers to the process of combining two images to create a single image that has the characteristics of both original images. The result is a combination of the corresponding pixel values of the two original images with weights.

The blending process involves specifying a weight for each pixel in one of the original images, computing (1 – weight) for each pixel in another image, and then merging them together to produce the output image. Blending images is a common operation in computer vision and image processing, and is used for a variety of applications, such as creating panoramas, compositing images, and generating special effects in videos and images.

Say, there are two images, Original Image 1 and Original Image2, as shown in Figures below.




 Blend Image: Original Image 1


Blend Image: Original Image 2

The OpenCV documents describe the algorithm to blend them together,

g( i , j ) = α f0 ( i , j ) + (1 − α) f1 ( i , j )

from OpenCV official document at https://docs.opencv.org/4.7.0/d5/dc4/tutorial_adding_images.html

f0 ( i , j ) and f1 ( i , j ) are the two original images, and g( i , j ) is the output image. α is the weight (value from 0 to 1) on the first image, (1 – α) is the weight on the second image.

By adjusting the value of α, we can achieve different blending effects. Same as the previous sections, cv2.addWeighted() function is used to blend the two images.

The blend() function is to be added to the ImageProcessing class:

1 def blend(self, blend, alpha, image=None):

2 if image is None:

3 image = self.image

4 blend = cv2.resize(blend, (image.shape[1], image.shape[0]))

5 result = cv2.addWeighted(image, alpha, blend, (1.0 - alpha), 0)

6 return result

Explanations:

Line 1 Define blend() function, the parameters are the image to blend, and alpha which is between 0 and 1.

Line 4 The two images must be in the same size, make them the same using cv2.resize().

Line 5 Use cv2.addWeighted() function to implement the blending algorithm.

Here are the main codes:


A trackbar is created for adjusting alpha from 0 to 100, with a default value of 50. The callback function change_alpha() divides the value by 100, then it’s from 0 to 1.0.

The result looks something like Figure shown below.


The default alpha of 50 makes the two original images blend evenly. By adjusting the alpha value, the output image will be changing. If alpha=100, the result becomes pure Original Image 1; if alpha=0, the result is pure Original Image 2. If the alpha is in between, the result is mixed, but the weight of each image is different based on the alpha value.

Share:

0 comments:

Post a Comment