4

I have created a frame using C++ with OpenCV and want to insert few lines of text into it.

The following code is used:

putText(frame, "My text here", cvPoint(30,30), 
    FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200,250), 1, CV_AA); 

But here, i want to write, assuming 2 separate lines, "hello" and "welcome". The problem here is \n and endl are not working. Also if possible to align the text to be middle of the frame.

Thank you very much.

4
  • 2
    you need 2 putText lines. (it's not a word processor) . also, please avoid c-api constructs like cvScalar, cvPoint, use Scalar and Point instead
    – berak
    Feb 8, 2015 at 12:40
  • How can i write the second line please? Feb 8, 2015 at 12:42
  • putText(frame, "2nd line", Point(30,30+20), ...);
    – berak
    Feb 8, 2015 at 12:43
  • 1
    Extended reading: Added ostream-like cv::putText helper function #313 Feb 8, 2015 at 14:34

1 Answer 1

10

You need to call putText() for each line separately. In order to calculate the position of each new line you can use getTextSize() which return the width and height of the text and the baseline. In Python you can do something like this:

    position = (30, 30)
    text = "Some text including newline \n characters."
    font_scale = 0.75
    color = (255, 0, 0)
    thickness = 3
    font = cv2.FONT_HERSHEY_SIMPLEX
    line_type = cv2.LINE_AA

    text_size, _ = cv2.getTextSize(text, font, font_scale, thickness)
    line_height = text_size[1] + 5
    x, y0 = position
    for i, line in enumerate(text.split("\n")):
        y = y0 + i * line_height
        cv2.putText(frame,
                    line,
                    (x, y),
                    font,
                    font_scale,
                    color,
                    thickness,
                    line_type)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.