解决opencv, cv2.puttext函数无法显示中文字符

背景: opencv内置的cv2.puttext函数不能显示中文字符,尝试了下列方法:
(1)cv2.freetype。没有这个库;
(2)opencv无法导入中文字体库;
(3)卸载opencv-python,安装opencv-python-headless, opencv- contrib-python

方法: 使用PIL库作为中转

  1. 下载中文字体库https://github.com/StellarCN/scp_zh/blob/master/fonts/SimHei.ttf
  2. 使用下述代码绘制中文字符
def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):
    """
    img:opecv格式
    cv2显示中文字符
    """
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "SimHei.ttf", textSize, encoding="utf-8")
    # 绘制文本
    draw.text(position, text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

猜你喜欢

转载自blog.csdn.net/weixin_43960499/article/details/130638422