HomeLanguagesOpenCV – Alpha blending and masking of images

OpenCV – Alpha blending and masking of images

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

We take these two images to blend :

gfg.png

apple.jpeg

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.

Python3




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.waitKey(0)
  
cv2.imshow("img 2",img2)
  
cv2.waitKey(0)
  
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)
  
    cv2.waitKey(0)
  
    choice = int(input("Enter 1 to continue and 0 to exit"))


Outputs:

alpha = 0.8

alpha = 0.5

Alpha masking:

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

Python3




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)


Output:

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32631 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7009 POSTS0 COMMENTS
Nicole Veronica
12138 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12236 POSTS0 COMMENTS
Shaida Kate Naidoo
7133 POSTS0 COMMENTS
Ted Musemwa
7402 POSTS0 COMMENTS
Thapelo Manthata
7092 POSTS0 COMMENTS
Umr Jansen
7106 POSTS0 COMMENTS