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.
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 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: