Open In App
Related Articles

OpenCV – Alpha blending and masking of images

Improve Article
Save Article
Like Article

Alpha blending is the process of overlaying a foreground image on a background image.

We take these two images to blend :



Steps :

  • First, we will import OpenCV.
  • We read the two images that we want to blend.
  • The images are displayed.
  • We have a while loop that runs while the choice is 1.
  • Enter an alpha value.
  • Use cv2.addWeighted() to add the weighted images.
  • We display and save the image as alpha_{image}.png.
  • To continue and try out more alpha values, press 1. Else press 0 to exit.


import cv2
img1 = cv2.imread('gfg.png')
img2 = cv2.imread('apple.jpeg')
img2 = cv2.resize(img2, img1.shape[1::-1])
cv2.imshow("img 1",img1)
cv2.imshow("img 2",img2)
choice = 1
while (choice) :
    alpha = float(input("Enter alpha value"))
    dst = cv2.addWeighted(img1, alpha , img2, 1-alpha, 0)
    cv2.imwrite('alpha_mask_.png', dst)
    img3 = cv2.imread('alpha_mask_.png')
    cv2.imshow("alpha blending 1",img3)
    choice = int(input("Enter 1 to continue and 0 to exit"))


alpha = 0.8

alpha = 0.5

Alpha masking:

We can create a black and white mask from an image with a transparent background.


import cv2
im = cv2.imread("spectacles.png", cv2.IMREAD_UNCHANGED)
_, mask = cv2.threshold(im[:, :, 3], 0, 255, cv2.THRESH_BINARY)
cv2.imwrite('mask.jpg', mask)


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 03 Jan, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials