0

I am am trying to use OpenCV to create an image from text. The image may or may not have an overlay that needs to be merged with it. The font of the Text needs to be needs to be different than the HERSHEY text that comes with the C++ interface of OpenCV. I saw in this post and others that it can be done using the cvFontQt and cvAddText.

I am using OpenCV 2.4.13 and Qt 5.6. In the sample code below I can output the first and third lines using cvPutText with cvFont and HERSHEY however the second line using cvAddText with cvFontQt does not display.

#include "stdafx.h"
#include "opencv2\core\core_c.h"        
#include "opencv2\highgui\highgui_c.h"  

int main()
{
    // Create a window for a container to hold the image
    cvNamedWindow("cvtest", CV_WINDOW_AUTOSIZE);

    IplImage *img = cvCreateImage(cvSize(600, 300), IPL_DEPTH_64F, 4);

    // Set the image background to white
    cvSet(img, cvScalar(255, 255, 255));

    CvFont font;

    cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5);
    cvPutText(img, "cvInitFont; cvPutText: First line.", cvPoint(4, 30), &font, cvScalar(255));

    CvFont fontqt = cvFontQt("Courier New", -1, cvScalar(0,0,255), CV_FONT_NORMAL, CV_STYLE_NORMAL, 0);
    cvAddText(img, "cvFontQV; cvAddText:   Second line.", cvPoint(4, 60), &fontqt);

    cvPutText(img, "cvInitFont; cvPutText: Third line.", cvPoint(4, 90), &font, cvScalar(255));

    cvShowImage("cvtest", img);

    cvWaitKey(0);

    cvSaveImage("C:\\OpenCvTest64F.jpg", img);

    // Cleanup
    cvDestroyAllWindows();
    cvReleaseImage(&img);

    return 0;
}

The resulting image ("C:\OpenCvTest64F.jpg"):

Output Image

Am I using cvFontQt or cvAddText incorrectly? Any thoughts on why it does not show up in the image?

Community
  • 1
  • 1
Tom
  • 3
  • 2

1 Answers1

0

Any specific reason why you are using floating point images? If not, try adjusting the image initialization to:

IplImage *img = cvCreateImage(cvSize(600, 300), IPL_DEPTH_8U, 3);

The use of a 3-channel 8-bit image seems to fix the problem.

Just a note - when assigning color to floating point images the value should be in the range [0, 1], not [0, 255]. Also, the C++ api is much nicer!

Frik
  • 1,054
  • 1
  • 13
  • 16
  • Thank you Frik!! That did the trick. I agree the C++ api is much nicer. I would use it if I didn't need mono-spaced font. – Tom Jun 15 '16 at 15:19