方法
下载语言包simsun.ttc
simsun.ttc是三种字体“宋体、新宋体、宋体-PUA”ttf文件的集合
百度网盘下载链接
提取码:smwx
封装函数
import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
def cv2AddChineseText(img, text, position, textColor, textSize):
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") # simsun.ttc语言包放在程序同级目录下
# 绘制文本
draw.text(position, text, textColor, font=fontStyle)
# 转换回OpenCV格式
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
调用函数
import cv2
from PIL import Image, ImageDraw, ImageFont
src = cv2.imread('./test.jpg')
image = cv2AddChineseText(src,"测试", (123, 123),(0, 255, 0), 30)
cv2.imshow('image', image)
cv2.waitKey()