python opencv的 puttxt显示中文的方法

2022-07-26,,,,

直接使用puttxt显示中文会显示为"?“的形式
目前已经解决,如下方法可以顺利打印出中文
其中”./simsun.ttc"是中文字体的文件,可以自己网上下载,或者留下邮箱

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

def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype("./simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
img = cv2.imread(img_path)
img_disposed = cv2ImgAddText(img, txt, 50, 50, (255, 0 , 0), 20)
cv2.imwrite(target_path, img_disposed)

本文地址:https://blog.csdn.net/weixin_42544131/article/details/110922136

《python opencv的 puttxt显示中文的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。