python-opencv| putText()无法显示中文 & 在图片上加中文

文章目录

  • 一 问题
  • 二 利用PIL库显示中文
      • 2.1 下载中文字体包
            • 2.1.1 直接git clone
            • 2.1.2 把文件夹复制至PIL文件夹下
      • 2.2 使用PIL库
            • 2.2.1 函数介绍
            • 2.2.2 全部代码

一 问题

在python-opencv官网看到有putText()函数后,开心的要死,结果运行出来这啥玩意?找了半天解决办法原来不支持中文??

# -*- coding: utf-8 -*-
import cv2

img = cv2.imread('../../static/img/img_tongue/crop.jpg')
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'舌头',(50,100), font, 1,(255,255,255),2,cv2.LINE_AA)
cv2.imshow('ori', img)
k = cv2.waitKey(0)

python-opencv| putText()无法显示中文 & 在图片上加中文_第1张图片

二 利用PIL库显示中文

2.1 下载中文字体包

2.1.1 直接git clone
git clone https://github.com/tracyone/program_font && cd program_font && ./install.sh

长这个样子
python-opencv| putText()无法显示中文 & 在图片上加中文_第2张图片
python-opencv| putText()无法显示中文 & 在图片上加中文_第3张图片

2.1.2 把文件夹复制至PIL文件夹下

(其他博文里说的“/use/share/fonts/MyFonts/目录下”,我也不懂这是啥目录。后来随便试了试,放在项目venv下面的PIL里,居然成了)

具体文件夹如下(至少我的是这样):该项目的venv——Lib——site-packages——PIL
D:\1Coding\FlaskCoding\venv\GraduationProject\Lib\site-packages\PIL

我把刚才的文件夹换了个名字嗷,program_font换成font了。
python-opencv| putText()无法显示中文 & 在图片上加中文_第4张图片

2.2 使用PIL库

2.2.1 函数介绍
def write_chinese(img, font_type, font_size,color, position, content):
    # 图像从OpenCV格式转换成PIL格式
    img_PIL = Image.fromarray(cv.cvtColor(img, cv.COLOR_BGR2RGB))
    # 字体  字体*.ttc的存放路径一般是: /usr/share/fonts/opentype/noto/ 查找指令locate *.ttc
    font = ImageFont.truetype(font_type, font_size)
    # 字体颜色
    # 文字输出位置
    # 输出内容
    draw = ImageDraw.Draw(img_PIL)
    draw.text(position, content, font=font, fill=color)
    # 转换回OpenCV格式
    img_OpenCV = cv.cvtColor(np.asarray(img_PIL), cv.COLOR_RGB2BGR)
    return img_OpenCV

函数可以直接用,这是示例。

img_res = write_chinese(img, 'font/simhei.ttf', 20,(255, 255, 255),  (60,25), '肾')

img:图像
font_type:字体文件所在地址。因为“simhei.ttf”在PIL/font文件夹下,所以写成这种’font/simhei.ttf’格式
font_size:字体大小
color:字体颜色
position:汉字左下角所在位置
content:汉字内容

2.2.2 全部代码
from PIL import ImageDraw,ImageFont,Image

def write_chinese(img, font_type, font_size,color, position, content):
    # 图像从OpenCV格式转换成PIL格式
    img_PIL = Image.fromarray(cv.cvtColor(img, cv.COLOR_BGR2RGB))
    # 字体  字体*.ttc的存放路径一般是: /usr/share/fonts/opentype/noto/ 查找指令locate *.ttc
    font = ImageFont.truetype(font_type, font_size)
    # 字体颜色
    # 文字输出位置
    # 输出内容
    draw = ImageDraw.Draw(img_PIL)
    draw.text(position, content, font=font, fill=color)
    # 转换回OpenCV格式
    img_OpenCV = cv.cvtColor(np.asarray(img_PIL), cv.COLOR_RGB2BGR)
    return img_OpenCV

img = cv.imread('../../static/img/img_tongue/crop.jpg')
img_res = write_chinese(img, 'font/simhei.ttf', 20,(255, 255, 255),  (60,25), '肾')
cv.imshow("res", img_res)
k = cv.waitKey(0)

img_res = cv.cvtColor(img_res, cv.COLOR_BGR2RGB)
save_path = r'D:\1Coding\GraduationProject\app\static\img\img_tongue\region_division.jpg'
cv.imwrite(save_path, cv.cvtColor(img_res, cv.COLOR_BGR2RGB))

加上画矩阵框框,结果是这样
python-opencv| putText()无法显示中文 & 在图片上加中文_第5张图片

你可能感兴趣的:(Python,图像处理)