pytho-opencv 在图片上添加中文描述

由于项目需要,要在图片上增加汉语描述,但是 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系统中添加中文字体库,大家可以自行搜索,这个我没有尝试,但是网上有一些教程可以参考。
【如有问题,欢迎评论指正!谢谢!】
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值