Understanding Weighted Image Blending in OpenCV

Hello everyone,

I am learning image processing using Python and OpenCV. I am working on an assignment where I need to blend two images using the cv2.addWeighted() function.

I understand that the weight of the first image increases from 0 to 1, while the weight of the second image decreases from 1 to 0.

My question is: Why do both images need to have the same dimensions when using cv2.addWeighted(), and what happens if their dimensions are different?

I would appreciate any explanation. Thank you!

Because addWeighted works pixel by pixel. For every pixel it does dst = src1alpha + src2beta + gamma, so it needs a matching pixel in the other image at the same position. If the sizes dont match there is nothing to pair up, and OpenCV stops with an assertion error about the sizes (the channel count and data type have to match too, so a grayscale image and a colour one will also fail).

Easy fix is to resize one image to the shape of the other before blending, like img2 = cv2.resize(img2, (img1.shape[1], img1.shape[0])). Note resize takes (width, height) while shape gives (height, width), that trips up a lot of people. If you dont want to stretch the picture you can crop both to the same region instead.

For your fade from 0 to 1 just loop alpha over a range and use beta = 1 - alpha each time, then show or save each frame.

1 Like

One small extension to the resize/crop options: if neither stretching nor cropping suits you, paste both images into same-size canvases with NumPy slicing and blend those. Also worth knowing that alpha and beta don’t have to sum to 1 — gamma shifts the result — and with uint8 images the output saturates at 0/255, so values outside the 0–1 range just clip rather than wrap.