How to put a text in an image in OpenCV using C++?

OpenCVC++Server Side ProgrammingProgramming

In OpenCV, we can put some text in the image by using puttext() function. This function is defined in <imgproc.hpp> header. To put text in an image, we first need to declare the matrix which will load the image.

Instead of loading an image in our program, we have filled matrix with white color, and then we put the text in that matrix. We need to define the text's starting point in the matrix, the text's font, the font's color and the font's weight.

The basic syntax of this method is as follows −


putText(image, "Text in Images", text_position,FONT_HERSHEY_COMPLEX, font_size,font_Color, font_weight);

The following program shows the way to put a text in an image in OpenCV.


using namespace cv;
using namespace std;
int main() {
   Mat image=Mat(400, 400, CV_8UC3, Scalar(255, 255, 255));//Creating an empty matrix filled with white color//
   Point text_position(80, 80);//Declaring the text position//
   int font_size = 1;//Declaring the font size//
   Scalar font_Color(0, 0, 0);//Declaring the color of the font//
   int font_weight = 2;//Declaring the font weight//
   putText(image, "Text in Images", text_position,FONT_HERSHEY_COMPLEX, font_size,font_Color, font_weight);//Putting the text in the matrix//
   imshow("Image", image);//Showing the image//
   waitKey(0);//Wait for Keystroke//
   return 0;


Published on 10-Mar-2021 08:02:50