且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在框架/图像中插入多行文本

更新时间:2023-12-04 12:34:40

您需要为每一行分别调用 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)