Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overlay text on image when working with cv::Mat type

I am using opencv 2.1. In my code I have a few images stored as Mat objects initialized like this:

Mat img1 = imread("img/stuff.pgm", CV_LOAD_IMAGE_GRAYSCALE);

I can display them properly using imshow() after my matrix operations are done. Now I want to add some text on the image to describe what has happened. Looking at the documentation it seems like cvPutText() would be the function I need. But when I try something like this:

cvPutText(result, "Differencing the two images.", cvPoint(30,30), &font, GREEN);

I get the following compile error: error: cannot convert ‘cv::Mat’ to ‘CvArr*’ for argument ‘1’ to ‘void cvPutText(CvArr*, const char*, CvPoint, const CvFont*, CvScalar)’

What do I need to do to be able to add some text when displaying this image?

like image 232
Aras Avatar asked Mar 03 '11 01:03

Aras


3 Answers

I was looking at the wrong place. I found the answer in the newer OpenCV documentation for cpp. There is a new function called putText() that accepts cv::Mat objects. So I tried this line and it works:

putText(result, "Differencing the two images.", cvPoint(30,30), 
    FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200,250), 1, CV_AA);

Hope this helps someone.

like image 100
Aras Avatar answered Sep 30 '22 04:09

Aras


For C++ basic use in OpenCV 3 or greater:

cv::putText(yourImageMat, 
            "Text to add",
            cv::Point(5,5), // Coordinates (Bottom-left corner of the text string in the image)
            cv::FONT_HERSHEY_COMPLEX_SMALL, // Font
            1.0, // Scale. 2.0 = 2x bigger
            cv::Scalar(255,255,255), // BGR Color
            1, // Line Thickness (Optional)
            cv:: LINE_AA); // Anti-alias (Optional, see version note)
    

See putText() in OpenCV 4 docs, or old 2.x docs .

Note: Versions before OpenCV 2.x use CV_AA instead of LINE_AA

like image 31
Stan James Avatar answered Sep 30 '22 03:09

Stan James


putText(result, "Differencing the two images.", cvPoint(30,30), 
    FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200,250), 1, CV_AA);

In the above line "result" should be a cvArr* or an IplImage*. but from the code provided here, I guess you are passing a cv::Mat object. So, you either need to convert it using cvarrToMat() or pass &result instead of result.

Hope it helps

like image 32
Bilal Saeed Avatar answered Sep 30 '22 04:09

Bilal Saeed