(a)Final Blended Image |
(b) Background Image (c)Foreground Image |
Alpha blending
Alpha blending is the process of overlaying a foreground image with transparency over a background Image. The transparent image is generally a PNG image.It consists of four channels (RGBA).The fourth channel is the alpha channel which holds the transparency magnitude.
Image (b) is a background image and image (c) is the foreground / overlay image.
Image (a) is the final blended image obtained by blending the overalay image using the alpha mask.
Below is the image(Fig d) of the alpha channel of the overlay image.
Image (b) is a background image and image (c) is the foreground / overlay image.
Image (a) is the final blended image obtained by blending the overalay image using the alpha mask.
Below is the image(Fig d) of the alpha channel of the overlay image.
At every pixel of the image, we blend the background and foreground image color(F) and background color (B) using the alpha mask. At every pixel value of alpha lie in range(0,255), a pixel intensity of 0 means black color and pixel instensity of 255 means white color. On the edge of the mask pixel intensity lies in the range of 0 to 255.This creates smooth blending on the edges.
The blending is done using the following equation.
If: alpha =1: output pixel color is foreground.
elif: alpha =0: output pixel color is background.
else: output pixel color is a mix of both depending upon the value of alpha.
I is the alpha blended image.
For our Image mask , pixel intensity range is (0,255).We normalize the image intensity range by dividing each pixel by 255.0 to reduce the range to (0 to 1).
Note : Alpha mask will be a float 2D matrix, In python2 divide it by 255.0 instead of 255 to make the result a floating number.
If you divide it by 255 ,it may automatically convert it into integer,so for an alpha value of 0.5 (i.e 50 % transparency) will truncate to 0 (integer part). This will cause non smooth edges as shown below.
Implementation in OpenCV and Python.
Let's go ahead and dive into some code.Create a new file, name it alpha_blend.py and insert the following source code.
Subscribe and Download Code.
If you like this post,.Subscribe
To download the code: Click here.
In this post, I assume you are familiar enough with Python and OpenCV, so most of the code is self-explanatory. If you have any doubt or question, feel free to ask anything in the comment.
Thanks.
Thanks for the great explanation and well-written code! This is very useful :)
ReplyDeleteThanks
Deleteawesome but how would we implement a weight to decide how transparent the overlay is? Thank You!
ReplyDeleteAlpha Channel constitute the weight of blending at each pixel location,
DeleteIf you want to add transparency also, you can multiply the alpha channel with a value in range [0,1].