Add text watermark to an image in C++

In this tutorial, we will learn how to add text watermark to an image in C++ using OpenCV. For doing so we are going to use OpenCV. Before proceeding further let’s first understand what is a text watermark.

Text Watermark: is a type of watermark in which text is used for watermarking. The text watermark is added to the images for making it difficult for the original image to be copied or used without permission.

When you add a watermark to an image you clearly indicate that this photo should not be copied or used without your permission.

Original image:

opencv C++ watermarking

Text watermarked image:




Add text watermark to an image in C++

Note:

  1. OpenCV C++ must be installed and linked to Visual Studio on your PC. (if you don’t know how to do it then click here.)
  2. If the image file that you want to add is in the directory of the project then just enter the name of the file with extension otherwise enter the full path of the file while entering the name of the image file in the below program.

Program to add text watermark to an image using OpenCV in C++

#include<opencv2/opencv.hpp>
#include<iostream>

using namespace std;
using namespace cv;

int main()
{
  Mat image;
  string file,text;

  /* Enter path of the file if the file is not in the directory of the project */
  cout << "\nEnter name of a image file with extension: ";

  /* cin function cannot read space. Hence we have used getline function here. */
  getline(cin, file);

  /* imread() is used to read an image file */
  image = imread(file);

  /* Checking if image object contains an image */
  if (image.data == 0)
  {
    cout << "\n\nError..!!\n";
    cout << "\nCheck=>";
    cout << "\n1. Desired image is in the folder of the project";
    cout << "\n2. You have mentioned extension of an image file\n";
    exit(0);
  }

  cout << "\nEnter text that you want to add as watermark on an image: ";
  cin >> text;

  /* adding text watermark on an image. Here point(10,30) is a start point for the text to be added. FONT_HERSHEY_SCRIPT_COMPLEX is a font of the text. '1' is a font scale. scalar object represents the color of the text and '2' is a thickness of the text. */
  putText(image, text, Point(10,30) , FONT_HERSHEY_SCRIPT_COMPLEX, 1, Scalar(102, 20, 0), 2);
  
  /* namedWindow() is used to create a window with the mentioned name. In our case, window name is 'Text watermarked image' */
  namedWindow("Text watermarked image", WINDOW_AUTOSIZE);

  /* imshow() is used to display an image */
  imshow("Text watermarked image", image);

  /* Press esc to exit */
  if (waitKey(0) == 27)
  {
    exit(0);
  }

  /* when everything done, close all windows */
  destroyAllWindows();

  return 0;
}

Input/Output:

Output image of C++ watermarking

You may also read:

  1. Morris Preorder Tree Traversal in C++
  2. How to show image in C++ using OpenCV


Leave a Reply

Your email address will not be published. Required fields are marked *