如何在框架/图像中插入多行文本 [英] How to insert multiple lines of text into frame/image
问题描述
我使用 C++ 和 OpenCV 创建了一个框架,并想在其中插入几行文本.
I have created a frame using C++ with OpenCV and want to insert few lines of text into it.
使用如下代码:
putText(frame, "My text here", cvPoint(30,30),
FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200,250), 1, CV_AA);
但在这里,我想写,假设有两行,你好"和欢迎".这里的问题是 \n 和 endl 不起作用.此外,如果可能的话,将文本对齐到框架的中间.
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.
非常感谢.
推荐答案
您需要为每一行分别调用 putText()
.为了计算每个新行的位置,您可以使用 getTextSize()
返回文本的宽度和高度以及基线.在 Python 中,您可以执行以下操作:
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)
这篇关于如何在框架/图像中插入多行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!