Watermark image using opencv in python
Hi, today we are going to learn how to add an image watermark to another image. We will use OpenCV to perform various type of image operations. We make this tutorial very easy to learn.
Add watermark to Image in Python using OpenCV
- Numpy library
- OpenCV library
here we use:
- Main image: ‘flower.jpg’
- Logo image: ‘logo.png’
Code : Python program to watermark an image using openCV
import cv2 import numpy as np #importing the main image image = cv2.imread('floWer.jpg') oH,oW = image.shape[:2] image = np.dstack([image, np.ones((oH,oW), dtype="uint8") * 255]) #importing the logo image lgo_img = cv2.imread('logo.png',cv2.IMREAD_UNCHANGED) #Resizing the image scl = 10 w = int(lgo_img.shape * scl / 100) h = int(lgo_img.shape * scl / 100) dim = (w,h) lgo = cv2.resize(lgo_img, dim, interpolation = cv2.INTER_AREA) lH,lW = lgo.shape[:2] #Blending ovr = np.zeros((oH,oW,4), dtype="uint8") ovr[oH - lH - 60:oH - 60, oW - lW - 10:oW - 10] = lgo final = image.copy() final = cv2.addWeighted(ovr,0.5,final,1.0,0,final) # ShoWing the result cv2.imshow("Combine Image",final) cv2.waitKey(0) cv2.destroyAllWindows()
- In the first section, we import the libraries.
- Then we import the Main image (‘Flower.jpg’). And stored into ‘image’ variable.
- We take the Height and Width into the ‘oH’,‘oW’ variable.
- Then we create a stack array in sequence depthwise of the image.
- Next, we import the logo image (‘logo.png’). And stored into ‘lgo_img’ variable.
- We resize the logo image with the help of scale. Here we scale the logo image by 20%.
- Then we take the height and width of the scaled logo image in to ‘lH’,’lW’ variable.
- We create a ‘ovr’ NumPy zero array with the size of the main image.
- In this ‘ovr’ array we put the logo image into the given position. Here it is the right-bottom corner.
- We create a ‘final’ variable and keep the duplicate/copy of the main image.
- Then we blend the ‘ovr’ and ‘final’ with with ‘final’ image.
- Finally, we get our desired Output image with watermark.
You may like to read:
- Color filtering with OpenCV in python
- Convert RGB to Binary Image in Python (Black and White)
- Convert Image to Base64 string in Python