zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【OpenCV 例程200篇】23. 图像添加中文文字(ImageDraw.Draw)

Opencv中文 添加 图像 文字 23 200 例程
2023-09-14 09:12:49 时间

『youcans 的 OpenCV 例程200篇 - 总目录』


【youcans 的 OpenCV 例程200篇】23. 图像添加中文文字

  1. OpenCV 不支持显示中文字符,使用 cv2.putText() 时添加的文本字符串不能包含中文字符(包括中文标点符号)。
  2. 在图像中添加中文字符,可以使用 python+opencv+PIL 实现,或使用 python+opencv+freetype 实现。

具体方法详见扩展例程 1.32。

扩展例程:1.32 图像中添加中文文字

    # 1.32 图像中添加中文文字
    imgBGR = cv2.imread("../images/imgLena.tif")  # 读取彩色图像(BGR)

    from PIL import Image, ImageDraw, ImageFont
    if (isinstance(imgBGR, np.ndarray)):  # 判断是否 OpenCV 图片类型
        imgPIL = Image.fromarray(cv2.cvtColor(imgBGR, cv2.COLOR_BGR2RGB))
    text = "OpenCV2021, 中文字体"
    pos = (50, 20)  # (left, top),字符串左上角坐标
    color = (255, 255, 255)  # 字体颜色
    textSize = 40
    drawPIL = ImageDraw.Draw(imgPIL)
    fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="utf-8")
    drawPIL.text(pos, text, color, font=fontText)
    imgPutText = cv2.cvtColor(np.asarray(imgPIL), cv2.COLOR_RGB2BGR)

    cv2.imshow("imgPutText", imgPutText)  # 显示叠加图像 imgAdd
    key = cv2.waitKey(0)  # 等待按键命令

在这里插入图片描述


(本节完)


版权声明:
youcans@xupt 原创作品,转载必须标注原文链接:(https://blog.csdn.net/youcans/article/details/125112487)
Copyright 2022 youcans, XUPT
Crated:2021-11-18

【第2章:图像的数值运算】
21. 图像的叠加
22. 图像添加非中文文字
23. 图像添加中文文字