opencv如何在图片上写汉字

这篇博客介绍了如何利用Python和C++的OpenCV库结合FreeType库,在图片上添加汉字。详细步骤包括:引入CvText.h和CvText.cpp文件,将libfreetype.so.6库复制到工程目录,最后提供了测试代码。
摘要由CSDN通过智能技术生成

1、python-opencv

# -*- coding: utf-8 -*- 
import cv2 
import numpy 
from PIL import Image, ImageDraw, ImageFont 
  
if __name__ == '__main__': 
  
 img_OpenCV = cv2.imread('img/IMG_20180508_134820.jpg') 
 # 图像从OpenCV格式转换成PIL格式 
 img_PIL = Image.fromarray(cv2.cvtColor(img_OpenCV, cv2.COLOR_BGR2RGB)) 
  
 # 字体 字体*.ttc的存放路径一般是: /usr/share/fonts/opentype/noto/ 查找指令locate *.ttc 
 font = ImageFont.truetype('NotoSansCJK-Black.ttc', 40) 
 # 字体颜色 
 fillColor = (255,0,0) 
 # 文字输出位置 
 position = (100,100) 
 # 输出内容 
 str = '在图片上输出中文'
  
 # 需要先把输出的中文字符转换成Unicode编码形式 
 if not isinstance(str, unicode): 
  str = str.decode('utf8') 
  
 draw = ImageDraw.Draw(img_PIL) 
 draw.text(position, str, font=font, fill=fillColor) 
 # 使用PIL中的save方法保存图片到本地 
 # img_PIL.save('02.jpg', 'jpeg') 
  
 # 转换回OpenCV格式 
 img_OpenCV = cv2.cvtColor(numpy.asarray(img_PIL),cv2.COLOR_RGB2BGR) 
#  cv2.imshow("print chinese to image",img_OpenCV) 
#  cv2.waitKey() 
 cv2.imwrite('03.jpg',img_OpenCV) 

2、c++ opencv

使用freetpye方式

1)、编写CvText.h,并放到工程include下面

#ifndef CVTEXT_H
#define CVTEXT_H

#include <opencv2/opencv.hpp>
#include <ft2build.h>
#include FT_FREETYPE_H

class CvText {
public:

    /**
     * 构造函数,初始化一个字体
     * @param fontName 字体名称
     */
    explicit CvText(const char *fontName);

    virtual ~CvText();

    /**
     * 设置字体属性,属性为空时保持默认值
     * @param type 类型
     * @param size 大小
     * @param underline 下划线
     * @param diaphaneity 透明度
     */
    void setFont(int *type, cv::Scalar *size = nullptr,
                 bool *underline = nullptr, float *diaphaneity = nullptr);

    /**
     * 恢复默认字体设置
     */
  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值