由于项目需要,要在图片上增加汉语描述,但是 python-opencv 中的方法:cv2.putText() 只能添加英文,汉语添加时候乱码。
这里分别针对 windows系统和Linux系统下进行图片上的中文显示。【直接上了代码】
Windows 系统下的方法
import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
if (isinstance(img, numpy.ndarray)): # judege OpenCV img type
print("turn type...")
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
# "font/simsun.ttc" is the Song format Chinese which in 'C:/Windows/fonts'
fontText = ImageFont.truetype(
"font/simsun.ttc", textSize, encoding="utf-8")
draw.text((left, top), text, textColor, font=fontText)#write words on imgs
# return the BGR img which corresponding to the cv2.imread format
return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
Linux(Centos)系统下的方法
import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
if (isinstance(img, numpy.ndarray)): # judege OpenCV img type
print("turn type...")
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
# "/usr/share/fonts/" the dir which store the font_type in LInux
fontText = ImageFont.truetype(
"/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc", textSize, encoding="utf-8")
# fontText = ImageFont.truetype(
# "wqy-zenhei.ttc", textSize, encoding="utf-8")
draw.text((left, top), text, textColor, font=fontText)#write words on imgs
# return the BGR img which corresponding to the cv2.imread format
return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
函数:cv2ImgAddText()参数定义:
img:是经过cv2.imread 读取之后的np.ndarray 数组
text::为需要增加的文本内容
left:左上角的X坐标
top:左上角的Y坐标
textColor:RGB颜色值
textSize:文本内容的大小(具体根据自己的图片大小设计)
函数调用测试代码
img = cv2.imread(r'****/JPEGImages/IMG_000001.jpg')
img = cv2ImgAddText(img, "大家好", 140, 60, (255, 255, 0), 20)
cv2.imshow("write Chinese img",img)
#or
#cv2.imwrite("path",img)
总结
可以看出上面的两个方法是一样的,不同的地方是Windows 和 Linux系统中的字体类型要找到就行了。
如果想要在Linux系统中添加中文字体库,大家可以自行搜索,这个我没有尝试,但是网上有一些教程可以参考。
【如有问题,欢迎评论指正!谢谢!】