图像处理(2)Python实现在图片上显示中文

  • opencv-python don’t support no-ascii char,因此不能直接用cv2在图片上显示中文,需要借助PIL这个包,如果没有安装,运行:
    pip install pillow
    
  • 代码如下:
    import numpy as np
    import cv2
    from PIL import ImageFont, ImageDraw, Image
    
    def putText(img, text, org, font_path, color=(0, 0, 255), font_size=20):
        """
        在图片上显示文字
        :param img: 输入的img, 通过cv2读取
        :param text: 要显示的文字
        :param org: 文字左上角坐标
        :param font_path: 字体路径
        :param color: 字体颜色, (B,G,R)
        :return:
        """
        img_pil = Image.fromarray(img)
        draw = ImageDraw.Draw(img_pil)
        b, g, r = color
        a = 0
        draw.text(org, text, font=ImageFont.truetype(font_path, font_size), fill=(b, g, r, a))
        img = np.array(img_pil)
        return img
    
    if __name__ == '__main__':
        font_path = r'C:\Users\gzp\Desktop\simsun.ttc'
        img = np.random.randint(0, 255, [224, 224, 3], np.uint8)
        img = putText(img, "你好呀,年轻人", (0, 0), font_path, (0, 0, 255), 32)
        cv2.imshow('', img)
        cv2.waitKey()
    
  • 其中宋体字体文件,可以在此处下载。该网站亦可下载其他字体文件。
  • demo
    在这里插入图片描述
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值