图片来自于https://www.deviantart.com/moodyblue/art/Molecules-Of-Motion-757613387

软硬件环境

  • ubuntu 18.04 64bit
  • anaconda with python 3.6
  • opencv 3.1.0
  • Pillow 3.4.2

问题

opencv中的cv2.putText方法可以将字符显示出来,不过遗憾的是,显示中文时会出现乱码。putText方法只支持ascii中的一个很小的子集,而不是unicode或者是utf字符。找了找源码,可以看出一点端倪/home/xugaoxiang/anaconda3/pkgs/opencv3-3.1.0-py36_0/include/opencv2/core.hpp,其它环境路径会有差异,可以通过文件名来查找。默认情况下,opencv使用的是`hershey`这种字体,而且不支持自定义字体。

//! Only a subset of Hershey fonts
//! <http://sources.isc.org/utils/misc/hershey-font.txt> are supported
enum HersheyFonts {
    FONT_HERSHEY_SIMPLEX        = 0, //!< normal size sans-serif font
    FONT_HERSHEY_PLAIN          = 1, //!< small size sans-serif font
    FONT_HERSHEY_DUPLEX         = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX)
    FONT_HERSHEY_COMPLEX        = 3, //!< normal size serif font
    FONT_HERSHEY_TRIPLEX        = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX)
    FONT_HERSHEY_COMPLEX_SMALL  = 5, //!< smaller version of FONT_HERSHEY_COMPLEX
    FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font
    FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX
    FONT_ITALIC                 = 16 //!< flag for italic font
};

代码实践

既然官方不支持,我们就找其它的方法,图片处理的话,第一感觉就是能不能用Pillow这个库,果然经过一番的查找资料(详细的请见参考资料),把乱码的问题给解决了。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-08-15 14:05:21
# @Author  : xugaoxiang (djstava@gmail.com)
# @Link    : link
# @Version : 1.0.0

# -*- coding: utf-8 -*-

import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont

if __name__ == '__main__':

    # opencv 读取本地图片文件, 数据类型是numpy.ndarray
    img_OpenCV = cv2.imread('dj.jpeg')

    # 将opencv图像格式转换成PIL格式, 数据类型是PIL.Image.Image
    img_PIL = Image.fromarray(cv2.cvtColor(img_OpenCV, cv2.COLOR_BGR2RGB))

    # 字体,默认的路径/usr/share/fonts/opentype/noto/NotoSansCJK-Black.ttc,我把它拷贝过来了
    font = ImageFont.truetype('NotoSansCJK-Black.ttc', 26)
    # 字体颜色
    fillColor = (0,0,255)
    # 文字输出位置
    position = (50,50)
    # 输出内容
    str = '\t\t\t\t\t\t\t\t\t\t\t\t我的独立博客: \nhttps://xugaoxiang.com'

    draw = ImageDraw.Draw(img_PIL)
    draw.text(position, str, font=font, fill=fillColor)

    # 转换回OpenCV格式
    img_OpenCV = cv2.cvtColor(numpy.asarray(img_PIL),cv2.COLOR_RGB2BGR)

    # 在窗口中显示
    cv2.imshow("image",img_OpenCV)

    while True:
        key = cv2.waitKey(1) & 0xFF

        if key == ord('q'):
            break

    cv2.destroyAllWindows()

执行效果如下

cv_zh

参考资料



Comments

comments powered by Disqus