OpenCV实现在图像中写入汉字

来源:互联网 发布:cnc数控加工中心编程 编辑:程序博客网 时间:2024/04/27 16:01

由于OpenCV自带的cvInitFont和cvPutText函数不支持向图像中写入中文,而FreeType是一个完全开源的、可扩展、可定制且可移植的字体引擎,它提供TrueType字体驱动的实现统一的接口来访问多种字体格式文件,它将字变成位图,进而用于显示。由于Freetype是GPL版权发布的库,和opencv版权并不一致,因此目前还没有合并到opencv扩展库中,本文讲诉在windows环境下安装利用Freetype。关于Freetype的细节访问http://www.freetype.org/

1:http://download.savannah.gnu.org/releases/freetype/

     上面这个链接有下载,找到最新版本的下载即可,目前最新的是2.7版本

而我需要静态库,已有前辈做了工作,http://sourceforge.net/projects/freetype/files/freetype2/2.5.1/,本文所用的版本是2.5.3,解压包,在freetype-2.5.3\builds\windows\路径下有vc6.0、vs2005、vs2008、vs2010这几个工程,重新编译,得到我们所想要的静态库。

vs2010下的方法步骤:

1. 打开freetype-2.5.3\builds\win32\vc2005下的freetype.vcproj,得到一个工程。

2. 依次点击“工具”->“选项”->“项目和解决方案”->“vc++ 目录”,设置包含文件,即添加freetype-2.5.3下的include文件夹

3. 依次点击“项目”->“freetype属性”->“配置属性”->“常规”,修改配置类型为动态库

4. 依次点击“项目”->“freetype属性”->“配置属性”->“C/C++”->“预处理器”,在“预处理器定义”这一行添加内容:DLL_EXPORT

5. 依次点击“项目”->“freetype属性”配置选择“Release Multithreaded”

6. 修改工程头文件 ftconfig.h

#ifndef FT_EXPORT
#ifdef __cplusplus
#define FT_EXPORT( x )   extern "C"   x
#else
#define FT_EXPORT( x )   extern   x
#endif

改为

#ifdef   DLL_EXPORT
#undef   DLL_EXPORT
#define DLL_EXPORT   __declspec(dllexport)
#else
#define DLL_EXPORT   __declspec(dllimport)
#endif /* !DLL_EXPORT */
#ifndef FT_EXPORT
#ifdef __cplusplus
#define FT_EXPORT( x ) extern "C" DLL_EXPORT x
#else
#define FT_EXPORT( x ) extern DLL_EXPORT x
#endif

7. 选择工程点击“重新生成解决方案”,在freetype-2.5.3\objs\win32\vc2010目录下就产生了freetype253_D.lib 和 freetype253_D.dll文件

至此,得到了我们所想要的静态库。

8. 新建一个工程Test,将freetype253_D.dll, freetype253_D.lib,CvxText.h,CvxText.cpp,simhei.ttf复制到工程目录下,将CvxText.h,CvxText.cpp添加到工程中,将freetype253_D.lib加入到库目录中。CvxText.h,CvxText.cpp代码摘录在下面。

9. 将CvxText.h中的#include <cv.h> #include <highgui.h> 用#include<opencv2/opencv.hpp>代替

10.  在CvxText.cpp文件首行添加#include"stdafx.h" ,在函数setFont末尾添加语句 FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0);

11. 在工具->选项->c++目录中的包含目录中添加freetype-2.5.3下的include文件夹(头文件)

12. 简单的测试代码

#include "stdafx.h"
#include "iostream"  
#include "CvxText.h"
using namespace std;  
int _tmain(int argc, _TCHAR* argv[])
{
IplImage *img=cvLoadImage("dansir.jpg");
CvxText text("simhei.ttf"); 
const char *msg = "IT狼在北京";
double p = 0.5; 
       double dfFontHeight = 80;
text.setFont(NULL, NULL, NULL, &p, &dfFontHeight);   // 透明处理 
// 设置字体输出参数  
text.restoreFont();  
text.putText(img, msg, cvPoint(100, 150), CV_RGB(255,0,0));


/*
 cvNamedWindow这句必须有,且第一个参数必须
 和cvShowImage函数的第一个参数相同,否则会产生
 多个窗口,且图像显示不全且很模糊
*/
cvNamedWindow("11", 0);   
cvShowImage("11",img);
cvWaitKey(0);  
system("pause");  
cvReleaseImage(&img);  
cvDestroyAllWindows();  
return 0;
}


原始的dansir.jpg如下:


加入汉字后的效果如下:


CvxText.h文件如下:

#pragma once
#ifndef OPENCV_CVX_TEXT_2007_08_31_H  
#define OPENCV_CVX_TEXT_2007_08_31_H  


/** 
* \file CvxText.h 
* \brief OpenCV汉字输出接口 

* 实现了汉字输出功能。 
*/  


#include <ft2build.h>  
#include FT_FREETYPE_H  
#include<opencv2/core/core.hpp>  
#include<opencv2/highgui/highgui.hpp> 
class CvxText
{
// 禁止copy  
  
   CvxText& operator=(const CvxText&);  
  
   //================================================================  
   //================================================================  
  
public:  
  
   /** 
    * 装载字库文件 
    */  
  
   CvxText(const char *freeType);  
   virtual ~CvxText();  
  
   //================================================================  
   //================================================================  
  
   /** 
    * 获取字体。目前有些参数尚不支持。 
    * 
    * \param font        字体类型, 目前不支持 
    * \param size        字体大小/空白比例/间隔比例/旋转角度 
    * \param underline   下画线 
    * \param diaphaneity 透明度 
    * 
    * \sa setFont, restoreFont 
    */  
  
   void getFont(int *type,  
      CvScalar *size=NULL, bool *underline=NULL, double *diaphaneity=NULL, double *dfFontHeight = NULL);  
  
   /** 
    * 设置字体。目前有些参数尚不支持。 
    * 
    * \param font        字体类型, 目前不支持 
    * \param size        字体大小/空白比例/间隔比例/旋转角度 
    * \param underline   下画线 
    * \param diaphaneity 透明度 
    * 
    * \sa getFont, restoreFont 
    */  
  
   void setFont(int *type,  
      CvScalar *size=NULL, bool *underline=NULL, double *diaphaneity=NULL,  double *dfFontHeight = NULL);  
  
   /** 
    * 恢复原始的字体设置。 
    * 
    * \sa getFont, setFont 
    */  
  
   void restoreFont();  
  
   //================================================================  
   //================================================================  
  
   /** 
    * 输出汉字(颜色默认为黑色)。遇到不能输出的字符将停止。 
    * 
    * \param img  输出的影象 
    * \param text 文本内容 
    * \param pos  文本位置 
    * 
    * \return 返回成功输出的字符长度,失败返回-1。 
    */  
  
   int putText(IplImage *img, const char    *text, CvPoint pos);  
  
   /** 
    * 输出汉字(颜色默认为黑色)。遇到不能输出的字符将停止。 
    * 
    * \param img  输出的影象 
    * \param text 文本内容 
    * \param pos  文本位置 
    * 
    * \return 返回成功输出的字符长度,失败返回-1。 
    */  
  
   int putText(IplImage *img, const wchar_t *text, CvPoint pos);  
  
   /** 
    * 输出汉字。遇到不能输出的字符将停止。 
    * 
    * \param img   输出的影象 
    * \param text  文本内容 
    * \param pos   文本位置 
    * \param color 文本颜色 
    * 
    * \return 返回成功输出的字符长度,失败返回-1。 
    */  
  
   int putText(IplImage *img, const char    *text, CvPoint pos, CvScalar color);  
  
   /** 
    * 输出汉字。遇到不能输出的字符将停止。 
    * 
    * \param img   输出的影象 
    * \param text  文本内容 
    * \param pos   文本位置 
    * \param color 文本颜色 
    * 
    * \return 返回成功输出的字符长度,失败返回-1。 
    */  
   int putText(IplImage *img, const wchar_t *text, CvPoint pos, CvScalar color);  
  
   //================================================================  
   //================================================================  
  
private:  
  
   // 输出当前字符, 更新m_pos位置  
  
   void putWChar(IplImage *img, wchar_t wc, CvPoint &pos, CvScalar color);  
  
   //================================================================  
   //================================================================  
  
private:  
  
   FT_Library   m_library;   // 字库  
   FT_Face      m_face;      // 字体  
  
   //================================================================  
   //================================================================  
  
   // 默认的字体输出参数  
  
   int         m_fontType;  
   CvScalar    m_fontSize;  
   bool        m_fontUnderline;  
   double       m_fontDiaphaneity;  
   double      m_dfFontHeight;
  
   //================================================================  
   //================================================================  
};  
  
#endif // OPENCV_CVX_TEXT_2007_08_31_H  

CvxText.cpp类如下:

#include "StdAfx.h"
#include "CvxText.h"
#include <wchar.h>  
#include <assert.h>  
#include <locale.h>  
#include <ctype.h>  


#include "CvxText.h"  


//====================================================================  
//====================================================================  


// 打开字库  


CvxText::CvxText(const char *freeType)  
{  
assert(freeType != NULL);  


m_dfFontHeight = 20.0F;


// 打开字库文件, 创建一个字体  


if(FT_Init_FreeType(&m_library))
{
throw;
}
if(FT_New_Face(m_library, freeType, 0, &m_face)) throw;  


// 设置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, CvScalar *size, bool *underline, double *diaphaneity, double *dfFontHeight)  
{  
if(type) *type = m_fontType;  
if(size) *size = m_fontSize;  
if(underline) *underline = m_fontUnderline;  
if(diaphaneity) *diaphaneity = m_fontDiaphaneity;  
if(dfFontHeight) *dfFontHeight = m_dfFontHeight;
}  


void CvxText::setFont(int *type, CvScalar *size, bool *underline, double *diaphaneity, double *dfFontHeight)  
{  
// 参数合法性检查  


if(type)  
{  
if(type >= 0) m_fontType = *type;  
}  
if(size)  
{  
m_fontSize.val[0] = fabs(size->val[0]);  
m_fontSize.val[1] = fabs(size->val[1]);  
m_fontSize.val[2] = fabs(size->val[2]);  
m_fontSize.val[3] = fabs(size->val[3]);  
}  
if(underline)  
{  
m_fontUnderline   = *underline;  
}  
if(diaphaneity)  
{  
m_fontDiaphaneity = *diaphaneity;  
}  
if(dfFontHeight)
{
m_dfFontHeight = *dfFontHeight;
}
}  


// 恢复原始的字体设置  


void CvxText::restoreFont()  
{  
m_fontType = 0;            // 字体类型(不支持)  


m_fontSize.val[0] = m_dfFontHeight;      // 字体大小  
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::putText(IplImage *img, const char    *text, CvPoint pos)  
{  
return putText(img, text, pos, CV_RGB(255,255,255));  
}  
int CvxText::putText(IplImage *img, const wchar_t *text, CvPoint pos)  
{  
return putText(img, text, pos, CV_RGB(255,255,255));  
}  


//  


int CvxText::putText(IplImage *img, const char    *text, CvPoint pos, CvScalar color)  
{  
if(img == NULL) return -1;  
if(text == NULL) 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::putText(IplImage *img, const wchar_t *text, CvPoint pos, CvScalar color)  
{  
if(img == NULL) return -1;  
if(text == NULL) return -1;  


//  


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


putWChar(img, text[i], pos, color);  
}  
return i;  
}  


// 输出当前字符, 更新m_pos位置  


void CvxText::putWChar(IplImage *img, wchar_t wc, CvPoint &pos, CvScalar 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  = ((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.val[0]*m_fontSize.val[1];  
double sep   = m_fontSize.val[0]*m_fontSize.val[2];  


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



0 0
原创粉丝点击