由于opencv中的cv2.putText不支持中文显示,这里使用Pillow来解决这个问题,我写了一个简单的demo。
1.cv2putText_chinese.py 这个文件主要定义了转换函数
import cv2
import numpy
from PIL import Image,ImageDraw,ImageFont
def cv2ImgAddText(img,text,left,top,textColor,textSize):
if(isinstance(img,numpy.ndarray)):
img=Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
draw =ImageDraw.Draw(img)
ttf="/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" #linux中的中文字体格式一般在/usr/share/fonts/opentype/noto下
fontStyle=ImageFont.truetype(
ttf,textSize,encoding="utf-8")
draw.text((left,top),text,textColor,font=fontStyle)
return cv2.cvtColor(numpy.asarray(img),cv2.COLOR_RGB2BGR)
2.test.py
import cv2
from cv2putText_chinese import cv2ImgAddText
if __name__ == '__main__':
bmp=cv2.imread('./black.jpg')
img=cv2ImgAddText(bmp,' 哈哈哈哈',10,15,(255,255,255),10)
cv2.imshow('show',img)
cv2.waitKey(2000)