Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert multiple lines of text into frame/image

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.

like image 672
user3651085 Avatar asked Oct 30 '25 16:10

user3651085


1 Answers

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)
like image 145
zardosht Avatar answered Nov 01 '25 08:11

zardosht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!