OpenCV putText () new line character

I use cv2.putText () to draw a text string on the image.

When I write:

cv2.putText(img, "This is \n some text", (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, 2) 

Text drawn in the image:

This is ? some text

I expected the text to be printed on a new line, since \n is an escape character for the new line, but draws instead ? .

Why is this happening? Am I doing something wrong?

+17
python opencv
source share
2 answers

Unfortunately, putText not properly handle \n characters. See relevant rejection request . You need to split the text yourself and make several putText calls, for example:

 text = "This is \n some text" y0, dy = 50, 4 for i, line in enumerate(text.split('\n')): y = y0 + i*dy cv2.putText(img, line, (50, y ), cv2.FONT_HERSHEY_SIMPLEX, 1, 2) 
+28
source share

If you are going to add data from several lines to video frames, then you need to add several lines to the putText () method, even if the above answer with a for loop does not work .

What you can do is use the "exec" function in python, which will take a string as input and display it in code.

Therefore, I suggest creating a small piece of Python code as a string, adding all the lines using the for loop, and execute it in the place you want, and it will also be displayed in different places. This case helped me add data to the video.

 stringexec = "" m=0 for i in TextList: stringexec = steval+"cv2.putText(frame, TextList[" + str(TextList.index(i))+"], (100, 100+"+str(m)+"), cv2.FONT_HERSHEY_COMPLEX, 0.5, (200, 100, 100), 1, cv2.LINE_AA)\n" m += 100 exec(stringexec) 
0
source share

All Articles