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:
- Include OpenCV Headers
#include <opencv2/opencv.hpp>
- Load the Image
cv::Mat image = cv::imread("input.jpg");
- Choose Text Properties
Set the text string, font, position, size, color, and thickness. - Use
putText()
Function
OpenCV provides theputText()
function to overlay text. - 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 asoutput.jpg
.