python opencv write Chinese text, English text

Hyperlink: Summary of commonly used methods for deep learning work, matrix dimension changes, pictures, videos and other operations, including (torch, numpy, opencv, etc.)


When opencv writes Chinese directly, it will be garbled, and cv2.putText() can only draw English.

Sample code:

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont


def image_add_text(img, text, left, top, text_color, text_size):
    # 判断是否是opencv图片类型,是就转换Image类型
    if isinstance(img, np.ndarray):
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

    # 创建一个可以在给定图像上绘制的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    font_style = ImageFont.truetype("font/simsun.ttc", text_size, encoding='utf-8')
    # 绘制文本
    draw.text((left, top), text, text_color, font=font_style)
    # 转换回opencv格式并返回
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)


if __name__ == '__main__':
    img = cv2.imread("1.jpg")
    img = cv2.resize(img, (1920, 1080))
    # opencv 直接绘制中文会乱码,用下面方法实现绘制中文
    cv2.putText(img, '你好,世界', (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0))
    # 绘制英文字
    cv2.putText(img, 'hello, world', (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0))
    # 绘制中文
    img = image_add_text(img, '你好,世界', 100, 130, (255, 0, 0), 20)
    # 绘制中文
    cv2.imshow("img", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Example effect:
insert image description here

Guess you like

Origin blog.csdn.net/qq_28949847/article/details/128578690