OpenCV putText()换行符号

Vip*_*pul 19 python opencv

我使用cv2.putText()在图像上绘制文本字符串.

我写的时候:

cv2.putText(img, "This is \n some text", (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, 2)
Run Code Online (Sandbox Code Playgroud)

图像上绘制的文字是:

This is ? some text

我期待文本在新行中打印,因为它\n是换行符的转义字符,但它会?在图像上绘制.

为什么会这样?难道我做错了什么 ?

ely*_*ase 31

遗憾的putText是没有正确处理\n符号.查看相关的拒绝拉取请求.您需要自己拆分文本并进行多次putText调用,例如:

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)
Run Code Online (Sandbox Code Playgroud)

  • `cv2.getTextSize` 可用于计算“好”`dy` - [完整示例](/sf/answers/3796429241/) (2认同)
  • 简短示例: (_, label_height), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, font_scale, 厚度) (2认同)

Yon*_*hik 7

我为这只海豚编写了一个实用函数:

from typing import Optional, Tuple

import cv2
import numpy as np


def add_text_to_image(
    image_rgb: np.ndarray,
    label: str,
    top_left_xy: Tuple = (0, 0),
    font_scale: float = 1,
    font_thickness: float = 1,
    font_face=cv2.FONT_HERSHEY_SIMPLEX,
    font_color_rgb: Tuple = (0, 0, 255),
    bg_color_rgb: Optional[Tuple] = None,
    outline_color_rgb: Optional[Tuple] = None,
    line_spacing: float = 1,
):
    """
    Adds text (including multi line text) to images.
    You can also control background color, outline color, and line spacing.

    outline color and line spacing adopted from: https://gist.github.com/EricCousineau-TRI/596f04c83da9b82d0389d3ea1d782592
    """
    OUTLINE_FONT_THICKNESS = 3 * font_thickness

    im_h, im_w = image_rgb.shape[:2]

    for line in label.splitlines():
        x, y = top_left_xy

        # ====== get text size
        if outline_color_rgb is None:
            get_text_size_font_thickness = font_thickness
        else:
            get_text_size_font_thickness = OUTLINE_FONT_THICKNESS

        (line_width, line_height_no_baseline), baseline = cv2.getTextSize(
            line,
            font_face,
            font_scale,
            get_text_size_font_thickness,
        )
        line_height = line_height_no_baseline + baseline

        if bg_color_rgb is not None and line:
            # === get actual mask sizes with regard to image crop
            if im_h - (y + line_height) <= 0:
                sz_h = max(im_h - y, 0)
            else:
                sz_h = line_height

            if im_w - (x + line_width) <= 0:
                sz_w = max(im_w - x, 0)
            else:
                sz_w = line_width

            # ==== add mask to image
            if sz_h > 0 and sz_w > 0:
                bg_mask = np.zeros((sz_h, sz_w, 3), np.uint8)
                bg_mask[:, :] = np.array(bg_color_rgb)
                image_rgb[
                    y : y + sz_h,
                    x : x + sz_w,
                ] = bg_mask

        # === add outline text to image
        if outline_color_rgb is not None:
            image_rgb = cv2.putText(
                image_rgb,
                line,
                (x, y + line_height_no_baseline),  # putText start bottom-left
                font_face,
                font_scale,
                outline_color_rgb,
                OUTLINE_FONT_THICKNESS,
                cv2.LINE_AA,
            )
        # === add text to image
        image_rgb = cv2.putText(
            image_rgb,
            line,
            (x, y + line_height_no_baseline),  # putText start bottom-left
            font_face,
            font_scale,
            font_color_rgb,
            font_thickness,
            cv2.LINE_AA,
        )
        top_left_xy = (x, y + int(line_height * line_spacing))

    return image_rgb
Run Code Online (Sandbox Code Playgroud)

以下是结果示例:

image = 200 * np.ones((550, 410, 3), dtype=np.uint8)

image = add_text_to_image(
    image,
    "New line\nDouble new line\n\nLine too longggggggggggggggggggggg",
    top_left_xy=(0, 10),
)
image = add_text_to_image(
    image,
    "Different font scale",
    font_scale=0.5,
    font_color_rgb=(0, 255, 0),
    top_left_xy=(0, 150),
)
image = add_text_to_image(
    image,
    "New line with bg\nDouble new line\n\nLine too longggggggggggggggggggggg",
    bg_color_rgb=(255, 255, 255),
    font_color_rgb=(255, 0, 0),
    top_left_xy=(0, 200),
)
image = add_text_to_image(
    image,
    "Different line specing,\noutline and font face",
    font_color_rgb=(0, 255, 255),
    outline_color_rgb=(0, 0, 0),
    top_left_xy=(0, 350),
    line_spacing=1.5,
    font_face=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
)
import matplotlib.pyplot as plt

plt.imshow(image)
plt.show()
Run Code Online (Sandbox Code Playgroud)

代码结果