python 通过opencv中的putText方法进行中文的文本绘制。putText本身不支撑对中文文本的图像绘制。所以需要借助中文字体进行中文的显示。
示例代码如下:适用于python3版本。如果是python2版本的,请将 if not isinstance(chinese, str):改为 if not isinstance(chinese, unicode ):
其中字体“simsun.ttc”,必须是已经安装的中文字体,不过会报"OSError: cannot open resource"的错误。
import numpy as np import cv2 from PIL import Image, ImageDraw,ImageFont def paint_chinese_opencv(im, chinese, pos, color): img_PIL = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)) font = ImageFont.truetype('simsun.ttc', 35) fillColor = color # 颜色 position = pos # 位置 if not isinstance(chinese, str): chinese = chinese.decode('utf-8') draw = ImageDraw.Draw(img_PIL) draw.text(position, chinese, font=font, fill=fillColor) img = cv2.cvtColor(np.asarray(img_PIL), cv2.COLOR_RGB2BGR) return img #Create a black image img = np.zeros((600,600,3),np.uint8) img = paint_chinese_opencv(img, '我爱Python', (100, 100), (255, 255, 255)) cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()