Background: The built-in cv2.puttext function of opencv cannot display Chinese characters. I tried the following methods:
(1) cv2.freetype. There is no such library;
(2) opencv cannot import the Chinese font library;
(3) Uninstall opencv-python and install opencv-python-headless, opencv-contrib-python
Method: Use the PIL library as a transit
- Download the Chinese font library https://github.com/StellarCN/scp_zh/blob/master/fonts/SimHei.ttf
- Use the following code to draw Chinese characters
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)