python opencv中文绘制

cv2.putText本身不支持中文,所以只能换一种方式实现,具体见代码:

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


def draw_text(img_bg: np.ndarray, info: str):
    font_face = cv2.FONT_HERSHEY_COMPLEX
    font_scale = 2
    thickness = 2
    text_size = cv2.getTextSize(info, font_face, font_scale, thickness)
    print(text_size)
    p_center = (int(512 / 2 - text_size[0][0] / 2), int(512 / 2 - text_size[0][1] / 2))
    # cv2.putText不支持中文
    cv2.putText(img_bg, info, p_center, font_face, font_scale, (255, 255, 255), thickness)


def cv2AddChineseText(img_bg, text, position, textColor, textSize):
    if isinstance(img_bg, np.ndarray):  # 判断是否OpenCV图片类型
        img_bg = Image.fromarray(cv2.cvtColor(img_bg, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img_bg)
    fontStyle = ImageFont.truetype("msyh.ttc", textSize, encoding="utf-8")
    draw.text(position, text, textColor, font=fontStyle)
    return cv2.cvtColor(np.asarray(img_bg), cv2.COLOR_RGB2BGR)


img = np.zeros([512, 512, 3], dtype=np.uint8)
for i in range(512):
    for j in range(512):
        img[i, j, :] = [i % 256, j % 256, (i + j) % 256]
draw_text(img, 'hello world!')
img = cv2AddChineseText(img, '你好,世界。', (100, 100), (255, 0, 0), 16)
cv2.imshow('res', img)
cv2.waitKey(0)
cv2.destroyAllWindows()




  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值