Watermark images using OpenCV | How to mark an image with OpenCV

Contents

This article was published as part of the Data Science Blogathon

In this article, we will learn how to watermark multiple images using OpenCV.

Topics to cover:

  1. What is a watermark?
  2. Resize images in OpenCV
  3. Create watermark using an image

1. What is a watermark?

A watermark is a logo, Company, text or pattern that is intentionally overlaid on different images and is used to protect image copyright.

Its main purpose is to promote a brand and make it difficult to copy or use the original image without the permission of the owner..

Professional organizations often use watermarks to prevent others from using their content after hosting it online..

Then, Have you ever thought about adding a watermark to your images? Good, I did it.

For instance, we write blogs and mention the source of external images. But, What about the images you create on your own? Wouldn't it be nice to leave your mark on them?

Hurray! Let's get started on this exciting task.

2. Resize images in OpenCV

Resizing is nothing more than scaling the image, what it means to resize the original image. We can increase or decrease the size of the image based on business requirements.

Resizing can be done in various ways.

1. Preserve aspect ratio. The aspect ratio of an image is the ratio of its width to its height.

  • Reduce or enlarge the image size

2. Does not preserve aspect ratio

  • Shrink width only / increase, shrink height only / increase

3. Change both width and height to specific values

Sounds great so far, but how do we do it in practice? The answer is OpenCV and its resize function (). Read more about OpenCV's resize feature in this documentation.

Cv2.resize function syntax ():
cv2.resize (src, dsize, interpolation)

  • src – source image
  • dsize: the desired size of the output image
  • interpolation – Wikipedia definition: It is a method to build (find) new data points based on the range of a discrete set of known data points.

Check out this documentation to read more about interpolation flags.

Now, let's take a sample picture and change its size. Below is our sample picture.

44364deer-9418003
Author's Image

Now, try to display it using OpenCV.

  1. import cv2
    img = cv2.imread('images/deer. JPG')
    cv2.imshow("Original Image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Below is what our image looks like when displayed using OpenCV. Como nuestra imagen es de alta resolution, only part of it is visible.

79507deer20before20resizing-8155746

Then, there is definitely a need to resize it. We need to decrease its size.

Steps to resize an image in OpenCV:

  • Read the image using cv2.imread ()
  • Set the new width and height.
  • Create a tuple for the new dimensions
  • Resize image using cv2.resize ()
  • If required, save resized image to computer using cv2.imwrite ()
  • Show the original images, resized using cv2.imshow ()

1. Preserve aspect ratio: reduces the image scale to 20% of its original size.

(We are reducing the size of the original image to 20% of its original size. Therefore, We will create a tuple for the new dimensions by calculating the 20% of original width, the 20% of original height).

  1. import cv2
    img = cv2.imread('images/deer. JPG')
    percent_of_scaling = 20
    new_width = int(img.shape[1] * percent_of_scaling/100)
    new_height = int(img.shape[0] * percent_of_scaling/100)
    new_dim = (new_width, new_height)
    resized_img = cv2.resize(img, new_dim, interpolation=cv2.INTER_AREA)
    filename="resized_img_aspect ratio.jpg"
    cv2.imwrite(filename, resized_img)
    cv2.imshow("Original Image", img)
    cv2.imshow("Resized Image", resized_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

The above code saves the resized image and displays the original resized images.

19874resized20deer-1114087

Well done. We have successfully resized our image taking into account the aspect ratio.

2. Without preserving the aspect ratio: just shrink / increase width, just shrink / increase height

The steps to resize will be the same as above. The only difference is that we keep either of the two dimensions unchanged.

  1. import cv2
    img = cv2.imread('images/deer. JPG')
    new_dim = (img.shape[1], 500) # changes height
    resized_img = cv2.resize(img, new_dim, interpolation=cv2.INTER_AREA)
    cv2.imshow("Original Image", img)
    cv2.imshow("Resized Image", resized_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Below are the pictures shown from the above code.

75562distorted20deer-6442633

The resized image is distorted and not the desired output.

3. Change both width and height to specific values

  1. import cv2
  2. img = cv2.imread ('images / deer.JPG ')
  3. new_dim = (450, 450)
  4. resized_img = cv2.resize (img, new_dim, interpolation = cv2.INTER_AREA)
  5. cv2.imshow (“Original image”, img)
  6. cv2.imshow (“resized image”, resized_img)
  7. cv2.waitKey (0)
  8. cv2.destroyAllWindows ()

Below are the pictures shown from the above code.

81666specific20resize-5118588

This looks kinda cool, but not as good as the output image with a preserved aspect ratio. That's why I prefer to resize while preserving the aspect ratio.

The next step is to see how to create a watermark.

Create watermark using an image

I chose to put a watermark with the image of my name. Make a picture of your name and try it on me.

65473watermark-3243336
Watermark Image

Steps to add the watermark in the center of an image:

Read and resize images (watermark image, input image) if required.

import cv2
img = cv2.imread('images/deer. JPG')
watermark = cv2.imread("watermark.PNG")

percent_of_scaling = 20
new_width = int(img.shape[1] * percent_of_scaling/100)
new_height = int(img.shape[0] * percent_of_scaling/100)
new_dim = (new_width, new_height)
resized_img = cv2.resize(img, new_dim, interpolation=cv2.INTER_AREA)

wm_scale = 40
wm_width = int(watermark.shape[1] * wm_scale/100)
wm_height = int(watermark.shape[0] * wm_scale/100)
wm_dim = (wm_width, wm_height)
resized_wm = cv2.resize(watermark, wm_dim, interpolation=cv2.INTER_AREA)

Define the logo position according to the new dimensions of the resized input image.

h_img, w_img, _ = resized_img.shape
center_y = int(h_img/2)
center_x = int(w_img/2)
h_wm, w_wm, _ = resized_wm.shape
top_y = center_y - int(h_wm / 2)
left_x = center_x - int(w_wm / 2)
bottom_y = top_y + h_wm
right_x = left_x + w_wm

Get the Rectangular region of interest (KING) y almacenarlo en una variable llamada ‘roi’.

roi = resized_img[top_y:bottom_y, left_x:right_x]

Overlay the resized watermark to the ROI using cv2.addWeighted ()and store it in a variable called 'result'.

result = cv2.addWeighted(King, 1, resized_wm, 0.3, 0)

Now, add this result to the resized input image

resized_img[top_y:bottom_y, left_x:right_x] = result

Save the resulting watermarked image to your computer

filename="watermarked_deer.jpg"
cv2.imwrite(filename, resized_img)

Display the resulting watermarked image

cv2.imshow("Resized Input Image", resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

¡Then! Below is the resulting watermarked image.

13873watermarked_deer-3759783

Up to now, we learned how to put a watermark on a single image. As our goal is to watermark multiple images, we need to create a list of all those input images and loop through them. Below are the pictures I will use.

63013all_images-1359651

Create a list of input images

  1. import os
    folderPath = "images"
    imgList = os.listdir(folderPath)
    imgList
61186list20output-3775418

Code to watermark multiple images

  1. import cv2
    watermark = cv2.imread("watermark.PNG")
    wm_scale = 40
    wm_width = int(watermark.shape[1] * wm_scale/100)
    wm_height = int(watermark.shape[0] * wm_scale/100)
    wm_dim = (wm_width, wm_height)
    resized_wm = cv2.resize(watermark, wm_dim, interpolation=cv2.INTER_AREA)
    h_wm, w_wm, _ = resized_wm.shape
    
    for image in  imgList:
        img = cv2.imread(f'{folderPath}/{image}')
        percent_of_scaling = 20
        new_width = int(img.shape[1] * percent_of_scaling/100)
        new_height = int(img.shape[0] * percent_of_scaling/100)
        new_dim = (new_width, new_height)
        resized_img = cv2.resize(img, new_dim, interpolation=cv2.INTER_AREA)
        h_img, w_img, _ = resized_img.shape
        center_y = int(h_img/2)
        center_x = int(w_img/2)
        top_y = center_y - int(h_wm / 2)
        left_x = center_x - int(w_wm / 2)
        bottom_y = top_y + h_wm
        right_x = left_x + w_wm
        roi = resized_img[top_y:bottom_y, left_x:right_x]
        result = cv2.addWeighted(King, 1, resized_wm, 0.3, 0)
        resized_img[top_y:bottom_y, left_x:right_x] = result
        filename = os.path.basename(image)
        cv2.imwrite("watermarked images/watermarked_"+filename, resized_img)
        cv2.imshow("Watermarked Image", resized_img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
16658watermarked_all-6649323

Finally, we are done with the watermark on all input images.

Final notes:

Thanks for reading to the conclusion. At the end of this article, we are familiar with working in some of the OpenCV operations: read multiple images, resize and watermark them.

I hope you enjoyed reading this article. Try it out on your own and feel free to share it with your fellow students..

References:

OpenCV documentation

Download the code file for this GitHub repository link.

Other blog posts of mine

Feel free to check out my other blog posts from my DataPeaker profile.

You can find me in LinkedIn, Twitter in case you want to connect. I would love to connect with you.

For an immediate exchange of thoughts, write to me [email protected].

The media shown in this article is not the property of DataPeaker and is used at the author's discretion.

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.

Datapeaker