Blending images using OpenCV

Maximinusjoshus
featurepreneur
Published in
3 min readApr 14, 2021

Have you ever wondered how blended images are created? What is actually happening under the hoods? Don’t worry, you are about to find it out in a minute. In this article, we will use OpenCV’s addWeighted method to demonstrate the blending of images.

Before watching some real action, let us see what the OpenCV documentation has to say about blending images:

The documentation says that image blending basically images addition, but different weights are given to images so that it gives a feeling of blending or transparency. Images are added as per the equation below:

By varying α from 0→1, you can perform a cool transition between one image to another.

The addWeighted() function

OpenCV-Python uses the addWeighted() function to blend images. The function and its parameters are as follows.

dst=cv.addWeighted(src1,
alpha,
src2,
beta,
gamma[, dst[, dtype]])

src1- first input array.
alpha- weight of the first array elements.
src2- second input array
beta- weight of second array elements
gamma- scalar added to each sum.
and two optional arguments which are not required for this demonstration.

Alpha and Beta are the weights we give for the first and second images respectively. So this basically means the image is more opaque when the weight is more and vice versa. And another point to be noted is that ß is always 1-α and α is always 1-ß. Now the formula by which addWeighted function adds the images is:

dst = α.src1 + ß.src2 + γ

where src1 and src2 are the input images, α and ß are the respective weights, dst is the output image array and γ is the gamma correctness of the image (which is beyond the scope of this article so for now let us assume it to be 0).

Let us see an OpenCV code implementation to blend the below two images:

Photo by Ali Abdul Rahman on Unsplash(left). Photo by Aaron Burden on Unsplash(right).
import cv2 as cv#read the images
img1 = cv.imread("D:\\medium_blogs\\underwater_lighted.jpg")
img2 = cv.imread("D:\\medium_blogs\\fish.jpg")
#Images have to be of the same size to be added
#so resize one image to the size of the other before adding
img2=cv.resize(img2, (3000,4000))
#add(or blend) the images
result = cv.addWeighted(img1, 0.3, img2, 0.7, 0)
#create a resizable window for the image
cv.namedWindow('result',cv.WINDOW_NORMAL)
#show the image on the screen
cv.imshow('result',result)
if cv.waitKey()==0:
cv.destroyAllWindows()

The output of the above code is the image below:

Since I have given more weight to the picture of fishes, it is more prominent in the resultant blended image. And that’s it. This is how you blend images using OpenCV.

THANK YOU.

--

--