gstreamer使用opencv在视频中写入中文


这几天有研究下,怎么在gstreamer中通过opencv来向视频中写入中文;下面就写一下实现过程吧。
原本OpenCV只能向视频画面中写入英文字符,本文结合第三方工具freetype2

安装freetype2与中文环境

sudo add-apt-repository ppa:glasen/freetype2
sudo apt update
sudo apt install freetype2-demos

安装完成后,还需要安装本地中文环境信息
Ubuntu默认安装的中文环境为zh_CN.utf8,然后很多windows的文档还是以GB2312或GBK编码保存的,因此十分有必要在Ubuntu下生成GBK或GB2312的locale否则还是不能写入中文字符:

  • 修改/var/lib/locales/supported.d/local文件,在文件中添加以下内容,若无此文件,则先创建文件
    zh_CN.GBK GBK
    zh_CN.GB2312 GB2312
  • 执行 sudo dpkg-reconfigure --force locales ,执行命令后出现图形界面,选择最后的中文字库
    确认后在输出的结果中会出现以下信息,耐心等待
    zh_CN.GB2312 done
    zh_CN.GBK done
    zh_CN.UTF8 done
    基本上选择这三种就可以了

makefile编写

CC =g++  -std=c++11 -pthread
CFLAGS = -g -Wall
SRCS = CvText.cpp tools.cpp show_chinese.cpp
PROG = test
FREETYPE_INCLUDE = -I  /usr/include/freetype2
OPENCV = `pkg-config  opencv --cflags --libs`
LIBS = $(OPENCV)  
$(PROG):$(SRCS) 
	$(CC) $(CFLAGS) $(FREETYPE_INCLUDE) -o $(PROG) $(SRCS) $(LIBS) -lfreetype

makefile主要需要链接freetype库,添加freetype2库的头文件目录,以及opencv相关目录
网上找了很多关于用Opencv洗中文字符的问题,结合freetype大都需要CvText.cpp,CvText.h,tools.cpp这三个文件。

CvText.cpp

#include <cwchar>
#include <clocale>
#include <cctype>
#include <utility>
#include "tools.h"
#include "CvText.h"

using namespace Utils;

CvText::CvText(const char *fontName,TextEncoding encoding) {
    ASSERT(fontName != nullptr, "字体名称为空");

    // 打开字库文件, 创建一个字体
    ASSERT(FT_Init_FreeType(&m_library) == 0,
           "初始化字库失败,请检查freetype库配置是否正确");
    ASSERT(FT_New_Face(m_library, fontName, 0, &m_face) == 0,
           "载入字体失败,请检查字体文件是否存在");

    //选择字符编码
    switch (encoding){
        case UTF8:
            FT_Select_Charmap(m_face,FT_ENCODING_UNICODE);
            m_textEncoding = "zh_CN.utf8";
            break;
        case GB2312:
            FT_Select_Charmap(m_face,FT_ENCODING_GB2312);
            m_textEncoding = "zh_CN.gb2312";
            break;
        default:
            ASSERT(false, "不支持的文本编码");
    }

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

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

// 设置文本属性
void CvText::setTextStyle(int fontSize, float spaceSize, float separatorSize, float fontDiaphaneity) {
    if(fontSize>0)
        m_fontSize = fontSize;
    if(spaceSize>0)
        m_spaceRatio = spaceSize;
    if(separatorSize>0)
        m_separatorRatio = separatorSize;
    if(fontDiaphaneity>0)
        m_fontDiaphaneity = fontDiaphaneity;
}

// 恢复默认的文本设置
void CvText::resetTextStyle() {
    m_fontSize = 20;        // 字体大小
    m_spaceRatio = 0.5;     // 空白字符大小比例
    m_separatorRatio = 0.1;     // 间隔大小比例
    m_fontDiaphaneity = 1.0;    // 透明度
}


int CvText::putText(cv::Mat &frame, std::string text, cv::Point pos, cv::Scalar color) {
    return putText(frame,text.c_str(),pos, std::move(color));
}

int CvText::putText(cv::Mat &frame, const char *text, cv::Point pos, cv::Scalar color) {

    if (frame.empty())
        return -1;
    if (text == nullptr)
        return -1;

    wchar_t *w_str ;
    int count = char2Wchar(text, w_str,m_textEncoding.c_str());
    //
    for (int i=0; i<count; ++i) {
        wchar_t wc = w_str[i];
        //如果是ascii字符(范围0~127),调整字体大小
        //因为ascii字符在同样的m_fontSize下更小,所以要放大1.15倍
        if(wc<128)
            FT_Set_Pixel_Sizes(m_face, (FT_UInt)(m_fontSize*1.15), 0);
        else
            FT_Set_Pixel_Sizes(m_face, (FT_UInt)m_fontSize, 0);
        // 输出当前的字符
        putWChar(frame, wc, pos, color);
    }
    delete(w_str);
    return count;
}

/**
 * 将char字符数组转换为wchar_t字符数组
 * @param src char字符数组
 * @param dst wchar_t字符数组
 * @param locale 语言环境,mbstowcs函数依赖此值来判断src的编码方式
 * @return 运行成功返回0,否则返回-1
 */
int CvText::char2Wchar(const char *&src, wchar_t *&dst, const char *locale)
{
    if (src == nullptr) {
        dst = nullptr;
        return -1;
    }
    // 设置C语言的字符集环境
    char *result = setlocale(LC_CTYPE, locale);
    // 检查设置编码是否成功,失败的话抛出异常"设置字符编码失败"等信息
    ASSERT(result != nullptr, "设置字符编码失败。\n"
                              "对于zh_CN.GBK或者zh_CN.GB2312编码,"
                              "先安装中文语言包,然后根据下面链接来设置:\n"
                              "https://blog.csdn.net/wenwenxiong/article/details/17116791\n");
    // 得到转化为需要的宽字符大小
    int w_size = (int)mbstowcs(nullptr, src, 0) + 1;
    // w_size = 0 说明mbstowcs返回值为-1。即在运行过程中遇到了非法字符(很有可能是locale没有设置正确)
    if (w_size == 0) {
        dst = nullptr;
        return -1;
    }
    // 分配内存
    dst = new wchar_t[w_size];
    // 把char字符数组转换为wchar_t字符数组
    auto ret =  (int)mbstowcs(dst, src, strlen(src)+1);
    // 恢复默认的字符编码,以免影响程序的其他部分
    setlocale(LC_CTYPE,"");
    return ret;
}


// 输出当前字符, 更新m_pos位置
void CvText::putWChar(cv::Mat &frame, wchar_t wc, cv::Point &pos, cv::Scalar color) {
    // 根据unicode生成字体的二值位图  
    IplImage img = IplImage(frame);

    FT_UInt glyph_index = FT_Get_Char_Index(m_face, (FT_ULong)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 = ((img.origin == 0) ? i : (rows - 1 - i)) * slot->bitmap.pitch + j / 8;

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

                if (r >= 0 && r < img.height && c >= 0 && c < img.width) {
                    CvScalar scalar = cvGet2D(&img, r, c);

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

    // 修改下一个字的输出位置
    double space = m_fontSize * m_spaceRatio;
    double sep = m_fontSize * m_separatorRatio;

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

CvText.h

/**
 * 使用freetype这个库,可以说是非常复杂。要保证程序源码、
 * setlocale和FT_Select_CharMap三者的编码一致,才不会乱码。
 *
 * 程序源码的编码很重要,编码不同,其中汉字的编码也不同;
 * setlocale是用来配置地域的信息,设置当前程序使用的本地化信息,
 * 很多函数依赖于这个函数的设置(比如mbstowcs函数,功能是将char
 * 字符串数组转换为wchar_t字符数组,依赖setlocale函数的设置来
 * 判断char字符数组的编码);FT_Select_CharMap是freetype库中
 * 用来设置字符编码的函数;因此,要想不出现乱码,这三者的编码必须
 * 要一样。
 *
 * 在我的程序中,三者的编码均为UTF-8
 *
 * 还有一个非常关键的问题,字体文件必须包含中文。
 */
#ifndef CV_TEXT_H
#define CV_TEXT_H

#include <opencv2/opencv.hpp>

#include <ft2build.h>
#include FT_FREETYPE_H

namespace Utils {
    class CvText {
    public:

        /**
         * 文本编码
         */
        typedef enum {
            UTF8, GB2312
        } TextEncoding;

        /**
         * 构造函数,初始化一个字体
         * @param fontName 字体名称
         * @param encoding putText函数的参数中的文本编码,
         * 需要和代码的编码一致,否则会出现乱码。
         * 目前仅支持UTF-8(很多IDE的源码默认编码)和GB2312(
         * Visual Studio中文环境下的默认编码)这两种编码。
         */
        explicit CvText(const char *fontName, TextEncoding encoding = TextEncoding::UTF8);

        virtual ~CvText();

        /**
         * 设置文本属性
         * @param fontSize 字体大小
         * @param spaceRatio 空格大小比例
         * @param separatorRatio 分隔符大小比例
         * @param fontDiaphaneity 透明度
         */
        void setTextStyle(int fontSize, float spaceRatio = 0.5f,
                          float separatorRatio = 0.1f, float fontDiaphaneity = 1.0f);

        /**
         * 恢复默认文本设置
         */
        void resetTextStyle();

        /**
         * 将text的内容放到frame的指定位置(pos),默认文本颜色为黑色。
         * @param frame 输出的影象
         * @param text 文本内容
         * @param pos 文本位置
         * @param color 文本颜色
         * @return 返回成功输出的字符长度,失败返回-1。
         */
        int putText(cv::Mat &frame, std::string text, cv::Point pos,
                    cv::Scalar color = cv::Scalar(0, 0, 0));

        /**
          * 将text的内容放到frame的指定位置(pos),默认颜色为黑色。
          * @param frame 输出的影象
          * @param text 文本内容
          * @param pos 文本位置
          * @param color 文本颜色
          * @return 返回成功输出的字符长度,失败返回-1。
          */
        int putText(cv::Mat &frame, const char *text, cv::Point pos,
                    cv::Scalar color = cv::Scalar(0, 0, 0));

        //私有函数区
    private:
        /**
         * 输出wc到frame的pos位置
         * @param frame 输出Mat
         * @param wc 字符
         * @param pos 位置
         * @param color 颜色
         */
        void putWChar(cv::Mat &frame, wchar_t wc, cv::Point &pos, cv::Scalar color);

        /**
         * 将char字符数组转换为wchar_t字符数组
         * @param src char字符数组
         * @param dst wchar_t字符数组
         * @param locale 语言环境,mbstowcs函数依赖此值来判断src的编码方式
         * @return 运行成功返回0,否则返回-1
         */
        int char2Wchar(const char *&src, wchar_t *&dst, const char *locale = "");

        //私有变量区
    private:
        FT_Library m_library;           // 字库
        FT_Face m_face;                 // 字体

        // 默认的字体输出参数
        int m_fontSize;                 // 字体大小
        float m_spaceRatio;             // 空白字符大小比例
        float m_separatorRatio;         // 字符间分隔距离大小比例
        float m_fontDiaphaneity;        // 透明度
        std::string m_textEncoding;     // 文本编码
    };
}
#endif // CV_TEXT_H

tools.cpp

#include <iostream>
#include <string>
#include "tools.h"

using namespace std;

void error(const string &filePath, const string &function, int line, const string &info) {
    //获取文件名
    unsigned long pos = filePath.find_last_of('/');
    string filename(filePath.substr(pos + 1));
    string err = "文件:" + filename + ",函数:" + function + ",行:" + to_string(line) + ">>  " + info;
    //抛出错误
    throw runtime_error(err);
}

void warning(const string &filePath, const string &function, int line, const string &info) {
    //获取文件名
    unsigned long pos = filePath.find_last_of('/');
    string filename(filePath.substr(pos + 1));
    string err = "文件:" + filename + ",函数:" + function + ",行:" + to_string(line) + ">>  " + info;
    //输出警告
    cerr << err << endl;
}

tools.h

#ifndef TOOLS_H
#define TOOLS_H

#include <string>

/**
 * condition为false时抛出错误,错误信息为error_message
 */
#define ASSERT(condition,error_message) \
    if (!(condition)){\
        error(__FILE__, __func__, __LINE__,error_message); \
    }
/**
 * condition为false时输出警告,错误信息为warning_message
 */
#define WARNING(condition,warning_message)\
    if (!(condition)){\
        warning(__FILE__, __func__, __LINE__,error_message); \
    }

void error(const std::string &filePath, const std::string &function,
           int line, const std::string &info);

void warning(const std::string &filePath, const std::string &function,
                    int line, const std::string &info);

/**
 * condition为true时不做任何动作;
 * condition为false时输出false_message,并返回false_value.
 */
#define IF(condition,false_message,false_value) \
    if (!(condition)){\
        std::cerr<<"Line:"<<__LINE__<<">>"<<(false_message)<<std::endl; \
        return (false_value); \
    }
#endif //TOOLS_H

如何在gstreamer中,向视频画面写入中文

首先你需要在获取视频原始图像数据的元件中,拿到第一手的视频数据,一般是RGB或者BGR格式的,用OpenCV的话,请使用BGR格式,因为OpenCV使用大端方式存储图像数据。
假设这是你的pipeline如下:
v4l2src device=/dev/video2 ! 'video/x-raw,format=BGR,width=1280,height=720' ! queue ! videoconvert ! omxh264enc insert-sps-pps=true ! queue ! rtph264pay ! udpsink host=192.168.1.100 port=5001
那么就可以在queue元件的srcpad上绑定一个回调函数,关键代码如下:

process_pad = gst_element_get_static_pad (data.process_queue, "src");
gst_pad_add_probe (process_pad, GST_PAD_PROBE_TYPE_BUFFER,(GstPadProbeCallback) cb_queue_data, NULL, NULL);
//创建CvText对象:
CvText* pText;
CvText text("/home/nvidia/steering_wheel/SimHei.ttf",CvText::UTF8);
pText = &text;
pText->setTextStyle(30, 0.5f, 0.1f, 1.0f);
// cb_queue_data回调函数读取数据,完成写入中文后,再将数据放回。此示例可能会造成视频延迟,可以用队列实现无延迟写入中文
static GstPadProbeReturn
cb_queue_data (GstPad          *pad,
              GstPadProbeInfo *info,
              gpointer         user_data)
{
     GstMapInfo map;
     GstBuffer *buffer;

     buffer = GST_PAD_PROBE_INFO_BUFFER (info);
     buffer = gst_buffer_make_writable (buffer);
     if (buffer == NULL) return GST_PAD_PROBE_OK;

     /* Mapping a buffer can fail (non-writable) */
     if (gst_buffer_map (buffer, &map, GST_MAP_WRITE))
     {  
          frame_count++;
          Mat frame(Size(1280, 720), CV_8UC3, (char*)map.data, Mat::AUTO_STEP);
          putText(frame, getTimeStamp(), Point(5, 25), FONT_HERSHEY_DUPLEX, 1, Scalar(255,255,255), 2);

          pText->putText(frame,"人工干预次数:", Point(5, 60),Scalar(255, 255, 255));
   
          gint size=frame.cols*frame.rows*3;
          //将处理后的图像数据copy至queue
          memcpy(map.data,frame.data,size);
          gst_buffer_unmap (buffer, &map);  
    }
  	GST_PAD_PROBE_INFO_DATA (info) = buffer;
  	return GST_PAD_PROBE_OK;
}	

猜你喜欢

转载自blog.csdn.net/zhaoyun_zzz/article/details/84173356