How to put a text in an image in opencv c++

Viewed 24130

I am currently working on my assignment and where I will load an image and display the same image with text in it. The problem is I don't know how to use the putText function.

This is the code I have right now:

cvInitFont(CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0, 0.0, 1, 8);

cvPutText(img, "You are drinking a lot of water. You may want to cut back.", cvPoint(20, 20), CV_FONT_HERSHEY_SIMPLEX, cvScalar(255, 0, 0));

Please help me. Thanks in advance.

1 Answers

Try something like this:

cv::Mat img(512, 512, CV_8UC3, cv::Scalar(0));

cv::putText(img, //target image
            "Hello, OpenCV!", //text
            cv::Point(10, img.rows / 2), //top-left position
            cv::FONT_HERSHEY_DUPLEX,
            1.0,
            CV_RGB(118, 185, 0), //font color
            2);

cv::imshow("Hello!", img);
cv::waitKey();

On a 512 * 512 black image, the code writes "Hello, OpenCV!"

This code is compatible with both OpenCV 2.x and 3.x.

Related