Ubuntu 下用opencv在图片上显示汉字。

本文介绍了一个基于OpenCV的中文文本渲染类CvxText,该类利用FreeType库支持中文汉字在图像上的输出,包括设置字体、大小、颜色等属性,并提供测试代码实现人脸识别后汉字显示的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CvxText.h

#ifndef OPENCV_CVX_TEXT_HPP_
#define OPENCV_CVX_TEXT_HPP_

// source from: http://www.opencv.org.cn/forum.php?mod=viewthread&tid=2083&extra=&page=1
// 支持OpenCV中文汉字输入

#include <ft2build.h>
#include FT_FREETYPE_H

#include <opencv2/opencv.hpp>

class CvxText {
public:
    /**
    * 装载字库文件
    */
    CvxText(const char* freeType);
    virtual ~CvxText();

    /**
    * 获取字体.目前有些参数尚不支持.
    *
    * \param font        字体类型, 目前不支持
    * \param size        字体大小/空白比例/间隔比例/旋转角度
    * \param underline   下画线
    * \param diaphaneity 透明度
    *
    * \sa setFont, restoreFont
    */
    void getFont(int* type, cv::Scalar* size=nullptr, bool* underline=nullptr, float* diaphaneity=nullptr);

    /**
    * 设置字体.目前有些参数尚不支持.
    *
    * \param font        字体类型, 目前不支持
    * \param size        字体大小/空白比例/间隔比例/旋转角度
    * \param underline   下画线
    * \param diaphaneity 透明度
    *
    * \sa getFont, restoreFont
    */
    void setFont(int* type, cv::Scalar* size=nullptr, bool* underline=nullptr, float* diaphaneity=nullptr);

    /**
    * 恢复原始的字体设置.
    *
    * \sa getFont, setFont
    */
    void restoreFont();

    /**
    * 输出汉字(颜色默认为黑色).遇到不能输出的字符将停止.
    *
    * \param img  输出的影象
    * \param text 文本内容
    * \param pos  文本位置
    *
    * \return 返回成功输出的字符长度,失败返回-1.
    */
    int putTextZ(cv::Mat& img, char* text, cv::Point pos);

    /**
    * 输出汉字(颜色默认为黑色).遇到不能输出的字符将停止.
    *
    * \param img  输出的影象
    * \param text 文本内容
    * \param pos  文本位置
    *
    * \return 返回成功输出的字符长度,失败返回-1.
    */
    int putTextZ(cv::Mat& img, const wchar_t* text, cv::Point pos);

    /**
    * 输出汉字.遇到不能输出的字符将停止.
    *
    * \param img   输出的影象
    * \param text  文本内容
    * \param pos   文本位置
    * \param color 文本颜色
    *
    * \return 返回成功输出的字符长度,失败返回-1.
    */
    int putTextZ(cv::Mat& img, const char* text, cv::Point pos, cv::Scalar color);

    /**
    * 输出汉字.遇到不能输出的字符将停止.
    *
    * \param img   输出的影象
    * \param text  文本内容
    * \param pos   文本位置
    * \param color 文本颜色
    *
    * \return 返回成功输出的字符长度,失败返回-1.
    */
    int putTextZ(cv::Mat& img, const wchar_t* text, cv::Point pos, cv::Scalar color);

private:
    // 禁止copy
    CvxText& operator=(const CvxText&);
    // 输出当前字符, 更新m_pos位置
    void putWChar(cv::Mat& img, wchar_t wc, cv::Point& pos, cv::Scalar color);

    FT_Library   m_library;   // 字库
    FT_Face      m_face;      // 字体

    // 默认的字体输出参数
    int         m_fontType;
    cv::Scalar   m_fontSize;
    bool      m_fontUnderline;
    float      m_fontDiaphaneity;
};

#endif // OPENCV_CVX_TEXT_HPP_

CvxText.cpp

#include <wchar.h>
#include <assert.h>
#include <locale.h>
#include <ctype.h>
#include <cmath>

#include "CvxText.h"

// 打开字库
CvxText::CvxText(const char* freeType)
{
    assert(freeType != NULL);

    // 打开字库文件, 创建一个字体
    if(FT_Init_FreeType(&m_library)) throw;
    if(FT_New_Face(m_library, freeType, 0, &m_face)) throw;

    // 设置字体输出参数
    restoreFont();

    // 设置C语言的字符集环境
    setlocale(LC_ALL, "");
}

// 释放FreeType资源
CvxText::~CvxText()
{
    FT_Done_Face(m_face);
    FT_Done_FreeType(m_library);
}

// 设置字体参数:
//
// font         - 字体类型, 目前不支持
// size         - 字体大小/空白比例/间隔比例/旋转角度
// underline   - 下画线
// diaphaneity   - 透明度
void CvxText::getFont(int* type, cv::Scalar* size, bool* underline, float* diaphaneity)
{
    if (type) *type = m_fontType;
    if (size) *size = m_fontSize;
    if (underline) *underline = m_fontUnderline;
    if (diaphaneity) *diaphaneity = m_fontDiaphaneity;
}

void CvxText::setFont(int* type, cv::Scalar* size, bool* underline, float* diaphaneity)
{
    // 参数合法性检查
    if (type) {
        if(type >= 0) m_fontType = *type;
    }
    if (size) {
        m_fontSize.val[0] = std::fabs(size->val[0]);
        m_fontSize.val[1] = std::fabs(size->val[1]);
        m_fontSize.val[2] = std::fabs(size->val[2]);
        m_fontSize.val[3] = std::fabs(size->val[3]);
    }
    if (underline) {
        m_fontUnderline   = *underline;
    }
    if (diaphaneity) {
        m_fontDiaphaneity = *diaphaneity;
    }

    FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0);
}

// 恢复原始的字体设置
void CvxText::restoreFont()
{
    m_fontType = 0;            // 字体类型(不支持)

    m_fontSize.val[0] = 20;      // 字体大小
    m_fontSize.val[1] = 0.5;   // 空白字符大小比例
    m_fontSize.val[2] = 0.1;   // 间隔大小比例
    m_fontSize.val[3] = 0;      // 旋转角度(不支持)

    m_fontUnderline   = false;   // 下画线(不支持)

    m_fontDiaphaneity = 1.0;   // 色彩比例(可产生透明效果)

    // 设置字符大小
    FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0);
}

// 输出函数(颜色默认为白色)
int CvxText::putTextZ(cv::Mat& img, char* text, cv::Point pos)
{
    return putTextZ(img, text, pos, CV_RGB(255, 255, 255));
}

/*int CvxText::putTextZ(cv::Mat& img, const wchar_t* text, cv::Point pos)
{
    return putTextZ(img, text, pos, CV_RGB(255,255,255));
}*/

int CvxText::putTextZ(cv::Mat& img, const char* text, cv::Point pos, cv::Scalar color)
{
    if (img.data == nullptr) return -1;
    if (text == nullptr) return -1;

    int i;
    for (i = 0; text[i] != '\0'; ++i) {
        wchar_t wc = text[i];

        // 解析双字节符号
        if(!isascii(wc)) mbtowc(&wc, &text[i++], 2);

        // 输出当前的字符
        putWChar(img, wc, pos, color);
    }

    return i;
}

int CvxText::putTextZ(cv::Mat& img, const wchar_t* text, cv::Point pos, cv::Scalar color)
{
    if (img.data == nullptr) return -1;
    if (text == nullptr) return -1;

    int i;
    for(i = 0; text[i] != '\0'; ++i) {
        // 输出当前的字符
        putWChar(img, text[i], pos, color);
    }

    return i;
}

// 输出当前字符, 更新m_pos位置
void CvxText::putWChar(cv::Mat& img, wchar_t wc, cv::Point& pos, cv::Scalar color)
{
    // 根据unicode生成字体的二值位图
    FT_UInt glyph_index = FT_Get_Char_Index(m_face, wc);
    FT_Load_Glyph(m_face, glyph_index, FT_LOAD_DEFAULT);
    FT_Render_Glyph(m_face->glyph, FT_RENDER_MODE_MONO);

    FT_GlyphSlot slot = m_face->glyph;

    // 行列数
    int rows = slot->bitmap.rows;
    int cols = slot->bitmap.width;

    for (int i = 0; i < rows; ++i) {
        for(int j = 0; j < cols; ++j) {
            int off  = i * slot->bitmap.pitch + j/8;

            if (slot->bitmap.buffer[off] & (0xC0 >> (j%8))) {
                int r = pos.y - (rows-1-i);
                int c = pos.x + j;

                if(r >= 0 && r < img.rows && c >= 0 && c < img.cols) {
                    cv::Vec3b pixel = img.at<cv::Vec3b>(cv::Point(c, r));
                    cv::Scalar scalar = cv::Scalar(pixel.val[0], pixel.val[1], pixel.val[2]);

                    // 进行色彩融合
                    float p = m_fontDiaphaneity;
                    for (int k = 0; k < 4; ++k) {
                        scalar.val[k] = scalar.val[k]*(1-p) + color.val[k]*p;
                    }

                    img.at<cv::Vec3b>(cv::Point(c, r))[0] = (unsigned char)(scalar.val[0]);
                    img.at<cv::Vec3b>(cv::Point(c, r))[1] = (unsigned char)(scalar.val[1]);
                    img.at<cv::Vec3b>(cv::Point(c, r))[2] = (unsigned char)(scalar.val[2]);
                }
            }
        }
    }

    // 修改下一个字的输出位置
    double space = m_fontSize.val[0]*m_fontSize.val[1];
    double sep   = m_fontSize.val[0]*m_fontSize.val[2];

    pos.x += (int)((cols? cols: space) + sep);
}

测试代码:人脸识别加汉字显示。

#include <iostream>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "time.h"
#include <fstream>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
#include <locale>
#include <string>
#include "CvxText.h"
#include <vector>
#include "CvxText.cpp"
//#include "puttextzh.cpp" 
#define  MY_SIZE	Size(90, 90)
using namespace cv;
using namespace std;
string getTime()   //获取系统时间 字符串
{
	time_t timep; //time_t类型
	time(&timep);
	char tmp[64]; //字符个数
	strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&timep)); //时间格式可调
	return tmp;
}

static int ToWchar(char* &src, wchar_t* &dest, const char *locale = "zh_CN.GB2312")
{
    if (src == NULL) {
        dest = NULL;
        return 0;
    }

    // 根据环境变量设置locale
    setlocale(LC_CTYPE, locale);

    // 得到转化为需要的宽字符大小
    int w_size = mbstowcs(NULL, src, 0) + 1;

    // w_size = 0 说明mbstowcs返回值为-1。即在运行过程中遇到了非法字符(很有可能使locale
    // 没有设置正确)
    if (w_size == 0) {
        dest = NULL;
        return -1;
    }

    //wcout << "w_size" << w_size << endl;
    dest = new wchar_t[w_size];
    if (!dest) {
        return -1;
    }

    int ret = mbstowcs(dest, src, strlen(src)+1);
    if (ret <= 0) {
        return -1;
    }
    return 0;
}






CascadeClassifier faceCascade;  //人脸检测的类
CascadeClassifier eyeClassifier;
//int putTextZ(cv::Mat& img, const char* text, cv::Point pos);
int main() {
	if (!faceCascade.load("./haarcascade_frontalface_alt.xml"))   //加载分类器,注意文件路径
			{
		cout << "导入haarcascade_frontalface_alt.xml时出错 !" << endl;
		return 0;
	}
	if (!eyeClassifier.load("./haarcascade_eye.xml"))    //把xml文档复制到现在用的文件夹下
			{
		cout << "导入haarcascade_eye.xml时出错 !" << endl;
		return 0;
	}

	VideoCapture cap;
	//cap.open(0);   //打开摄像头
	cap.open("33.mp4");   //打开视频
	Mat img, imgGray;
	vector < Rect > faces;
	vector < Rect > eyes;
	int c = 0;
	if (!cap.isOpened()) {
		return 1;
	}

	while (c != 27) //按键ESC的ASC码值.按下则退出
	{
		cap >> img;    //读取帧
		if (img.channels() == 3)    //三通道红绿蓝,彩色图像
				{
			cvtColor(img, imgGray, CV_RGB2GRAY);   //变成灰色图像
		} else {
			imgGray = img;
		}

		
		
		
		
		
		//Mat equalizedImg;
		//equalizeHist(imgGray, imgGray);//直方图均衡化

		eyeClassifier.detectMultiScale(imgGray, eyes, 1.4, 8,
				0 | CV_HAAR_SCALE_IMAGE, Size(10, 10));
		//1.4搜索窗口的比例系数,每次搜索依次扩大的百分比.
		//8  如果组成检测目标的小矩形的个数和小于8都会被排除.
		// 0或   CV_HAAR_DO_CANNY_PRUNING  :将会使用Canny边缘检测来排除边缘过多或过少的区域
		if (eyes.size() > 0) {
			for (size_t i = 0; i < eyes.size(); i++)      //eyeidx是啥,哪来的
					{
				//rectangle(imgGray, eyes[i], Scalar(0, 0, 255)); //用矩形画出检测到的眼睛的位置(黑色)
			}
		}
		//void putTextZH(cv::Mat &dst, const char* str, cv::Point org, cv::Scalar color, int fontSize,
		   // const char *fn = "Arial", bool italic = false, bool underline = false);
		faceCascade.detectMultiScale(imgGray, faces, 1.3, 6, 0, Size(20, 20)); //检测人脸

		if (faces.size() > 0) 
		{
			for (int i = 0; i < faces.size(); i++) 
			{
				rectangle(imgGray, Point(faces[i].x, faces[i].y),Point(faces[i].x + faces[i].width,faces[i].y + faces[i].height),Scalar(0, 255, 0), 1, 8);    //框出人脸位置
				string time = getTime();    //获取系统日期
				//如何显示中文
				//CvxText text("msyh.ttf");
				//putText(imgGray, "你好", Point(faces[i].x, faces[i].y),FONT_HERSHEY_SIMPLEX, 1, Scalar(255, 0, 225), 2, 8);
				//putText(imgGray,"地111112y方",Point(faces[i].x,faces[i].y),FONT_HERSHEY_SIMPLEX,1,Scalar(255,0,225),2,8);
				//putTextZH(imgGray, "OpenCV欢迎你", Point(50, 100), Scalar(255, 0, 0), 30, "微软雅黑");
				//text.putText(imgGray, w_str, Point(50, 100), Scalar(255, 0, 0)); //坐标,字体类型,大小,颜色,粗细,线型.
				//resize(img, img, cv::Size(300,300));
				
				CvxText text("./simhei.ttf"); //指定字体
						    cv::Scalar size1{ 50, 0.5, 0.1, 0 }; // (字体大小, 无效的, 字符间距, 无效的 }
						    text.setFont(nullptr, &size1, nullptr, 0);
						    char* str = (char *)" 许小鹏 ";
						    wchar_t *w_str;
						    ToWchar(str,w_str);
						    text.putText(imgGray, w_str, cv::Point(faces[i].x, faces[i].y), cv::Scalar(0, 0, 255));
				
				Mat faceROI;
				int count = 0;
				string tmp_path;
				faceROI = imgGray(faces[i]); //ROI部分为将要保存的图片
				resize(faceROI, faceROI, MY_SIZE);	//调整ROI图片大小到指定大小
				//tmp_path = format("%d.jpg", count++);
				//	my_path = dir_name + tmp_path;
				//imwrite(time + "jt.jpg", faceROI);		//保存采集到的图片到指定目录

			}
		}

		/*faceCascade.detectMultiScale(imgGray, faces, 1.2, 6, 0 | CV_HAAR_SCALE_IMAGE, Size(0, 0));
		 for (size_t i = 0; i < faces.size(); i++)
		 {
		 rectangle(img, faces[i], Scalar(0, 255, 255));           //用矩形画出检测到脸部的位置(黄色)
		 }*/

		namedWindow("v", 2);     //可调整窗口
		imshow("v", imgGray);   //一帧一帧图片进行播放
		c = waitKey(1);  //延迟时间
	}

	/*        //int k=0;
	 string time = getTime();//获取系统日期
	 if(c=32)
	 {
	 //Mat roi=imgGray[faces[i].x:faces[i].x + faces[i].width,faces[i].y:faces[i].y + faces[i].height];
	 imwrite(time+"jt.jpg",imgGray);//截图
	 }*/
	return 0;
}

执行代码:

g++ -o video video.cpp  `pkg-config --cflags --libs opencv` -lfreetype

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值