How do I add a watermark to an image using Python?

How do I add a watermark to an image using Python?

To put a watermark on a picture with Python, you can use tools like OpenCV and Pillow (PIL). Here's an easy guide on how to do it:

  1. Install the necessary libraries If you haven't done so yet:

     pip install opencv-python-headless pillow
  2. Create your watermark image (e.g., watermark.png) with transparency. Use an image editing program like Photoshop or an online tool to make a watermark image.

  3. Write Python code to add the watermark to your image:

import cv2
import numpy as np
from PIL import Image

# Load the main image
image_path = 'your_image.jpg'  # Replace with your image file path
image = cv2.imread(image_path)

# Load the watermark image with transparency
watermark_path = 'watermark.png'  # Replace with your watermark file path
watermark = cv2.imread(watermark_path, cv2.IMREAD_UNCHANGED)

# Get the dimensions of the main image
height, width, _ = image.shape

# Resize the watermark image to fit the main image
watermark = cv2.resize(watermark, (width, height))

# Create a mask for the watermark using the alpha channel
alpha_channel = watermark[:, :, 3] / 255.0
alpha_channel = np.expand_dims(alpha_channel, axis=2)

# Blend the main image and watermark using the alpha channel
blended_image = image * (1 - alpha_channel) + watermark[:, :, :3] * alpha_channel

# Convert the result to the proper image format (BGR to RGB)
blended_image_rgb = cv2.cvtColor(blended_image, cv2.COLOR_BGR2RGB)

# Convert the result to a PIL Image
result_image = Image.fromarray(blended_image_rgb)

# Save or display the result'output_image.jpg')  # Save the image with the watermark  # Display the image with the watermark

Change 'your_image.jpg' to the path of your input image and 'watermark.png' to the path of your watermark image. The code will mix the watermark image with the main image and save the outcome as 'output_image.jpg'.

Be sure to change the transparency and location of your watermark image to fit your needs. You can try different positions and levels of see-throughness to get the result you want.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!