Predictive Hacks

Blending Images with OpenCV

Most of us have noticed the “Facebook Rainbow Filter”. This is an example of “Blending Images” where we have the target image and we add a layer on top of it.

Blending  Images with OpenCV 1

In this tutorial, we will give a walk-through example of how we can blend images using Python OpenCV. Below we represent the target and the filter images.

Target Image

Blending  Images with OpenCV 2

Filter Image

Blending  Images with OpenCV 3
import cv2

# Two images
img1 = cv2.imread('target.jpg')
img2 = cv2.imread('filter.png')

# OpenCV expects to get BGR images, so we will convert from BGR to RGB

img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)

# Resize the Images. In order to blend them, the two images
# must be of the same shape

img1 =cv2.resize(img1,(620,350))
img2 =cv2.resize(img2,(620,350))


# Now, we can blend them, we need to define the weight (alpha) of the target image
# as well as the weight of the filter image
# in our case we choose 80% target and 20% filter
blended = cv2.addWeighted(src1=img1,alpha=0.8,src2=img2,beta=0.2,gamma=0)

# finally we can save the image. Now we need to convert it from RGB to BGR

cv2.imwrite('Blending.png',cv2.cvtColor(blended, cv2.COLOR_RGB2BGR))

And voilà!

Blending  Images with OpenCV 4

NB: There was no need to convert from BGR to RGB and then from RGB to BGR. We just included this step, in case you wanted to see the images throughout the process since matplotlib expects RGB images.

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

1 thought on “Blending Images with OpenCV”

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

data science journey
Miscellaneous

My Journey as a Data Science Blogger

Μy Background My Studies Back in 2001, I entered university to study Statistics. During my first year, I ran my