Insert Text on an Image Using C++

In this blog, we will learn how to insert or overlay text on an image using C++. This is commonly used for adding labels, watermarks, or annotations on photos. We’ll use the popular OpenCV library for this task.

 Insert text on an image using C++ program

Requirements:

  • C++ compiler
  • OpenCV installed
    sudo apt install libopencv-dev
    

 

Steps to Insert Text on Image:

  1. Include OpenCV Headers
    #include <opencv2/opencv.hpp>
    

     

  2. Load the Image
    cv::Mat image = cv::imread("input.jpg");
    

     

  3. Choose Text Properties
    Set the text string, font, position, size, color, and thickness.
  4. Use putText() Function
    OpenCV provides the putText() function to overlay text.
  5. Save the Image
    Write the result to a new image file.

Full Example Code:

#include <opencv2/opencv.hpp>
using namespace cv;

int main() {
    Mat image = imread("input.jpg");

    if (image.empty()) {
        std::cerr << "Could not read the image\n";
        return 1;
    }

    std::string text = "CodersPacket!";
    Point position(50, 100);
    int font = FONT_HERSHEY_SIMPLEX;
    double scale = 1;
    Scalar textColor(0, 255, 0);
    int lineThickness = 2;

    putText(image, text, position, font, scale, textColor, lineThickness);

    imwrite("output.jpg", image);

    std::cout << "Text added successfully!\n";
    return 0;
}

Compile & Run:

Compile:

g++ insert_text.cpp -o insert_text `pkg-config --cflags --libs opencv4`

Run:

./insert_text

Output:

The program loads input.jpg, adds the text

“CodersPacket!”

at position (50,100) in green, and saves it as output.jpg.

Leave a Comment

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

Scroll to Top