Blending And Watermarking Images In Python Using OpenCV

Using OpenCV and Python, it is very easy to blend images. One such example is watermarking images.
Import the necessary libraries 
  1. import cv2
    import numpy as np
    import matplotlib.pyplot as plt
Import the image you would like to watermark. OpenCV reads images as BGR. So we need to convert it to RGB channel, othterwise the Blue and Red channels will be seen as  swapped when you run plt.imshow
  1. img1 = cv2.imread('familyphoto.jpg' )
    img_rgb = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
Now comes the fun part. We will use numpy to create a blank image of the exact same size of our image that we want to watermark.
Also make sure to mention the datatype the same as that of the original image while creating this blank image.
  1. # Check data type of original image  
  2. print('image dtype ',img_rgb.dtype)  
  1. # Notice the usage of shape attribute to create image of exact same size. Zeros is to create a black image    
  2. blank_img = np.zeros(shape=(img_rgb.shape[0],img_rgb.shape[1],3), dtype=np.uint8)    
Now on this blank image we use the OpenCV's putText function to write our desired text mentioning font details.  The org attribute is origin x, y of start of text. Notice the flip of x and y with the image shape when figuring out the distances of text placement.
  1. # notice flip of x and y or org with image shape
  2. font = cv2.FONT_HERSHEY_SIMPLEX  
  3. cv2.putText(blank_img,  
  4.             text='DO NOT COPY',  
  5.             org=(img_rgb.shape[1]//8img_rgb.shape[0]//2),   
  6.             fontFace=font,  
  7.             fontScale= 4,color=(255,0,0),  
  8.             thickness=10,  
  9.             lineType=cv2.LINE_4)  
  10. plt.imshow(blank_img);  
With OpenCV drawing functions, you can create many different watermarks - your imagination is the limit.
Now we can easily blend these images using OpenCV's addWeighted function that takes the following format
image1 * alpha + image2 *  beta + gamma
  1. # original image is made a little light and watermark dark  
  2. blended = cv2.addWeighted(src1=img_rgb,alpha=0.7,src2=blank_img,beta=1, gamma = 0)  
  3. plt.imshow(blended);
You can disk save your watermarked image as follows:
  1. # make sure to use the correct color channels  
  2. cv2.imwrite('familyphoto_watermarked.jpg', cv2.cvtColor(blended, cv2.COLOR_RGB2BGR))  
Now, you can do this entire process in bulk in just a few seconds. 

Similar Articles