Using OpenCV and Python, it is very easy to blend images. One such example is watermarking images.
-
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
- img1 = cv2.imread('familyphoto.jpg' )
img_rgb = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb);
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.
-
- print('image dtype ',img_rgb.dtype)
-
- 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.
- # notice flip of x and y or org with image shape
- font = cv2.FONT_HERSHEY_SIMPLEX
- cv2.putText(blank_img,
- text='DO NOT COPY',
- org=(img_rgb.shape[1]//8, img_rgb.shape[0]//2),
- fontFace=font,
- fontScale= 4,color=(255,0,0),
- thickness=10,
- lineType=cv2.LINE_4)
- 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
-
- blended = cv2.addWeighted(src1=img_rgb,alpha=0.7,src2=blank_img,beta=1, gamma = 0)
- plt.imshow(blended);
You can disk save your watermarked image as follows:
-
- 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.