Opencv 处理图片增加文字

转自:
http://www.oschina.net/code/snippet_1447359_36028
1. 将头文件和源文件加入工程

2. ImageText.cpp 实例程序

3. 编译命令
g++ `pkg-config --cflags opencv` -o ImageText CvxText.cpp ImageText.cpp `pkg-config --libs opencv`

4. 大部分linux环境安装了freetype和freetype2两个版本,编译时头文件错误
  软连接目录/usr/include/freetype -> /usr/include/freetype2/freetype/
  
5. TTF字体可使用windows中的字体文件
标签:  OpenCV

代码片段(3)[全屏查看所有代码]

1. [代码]中文支持头文件     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//====================================================================
//====================================================================
//
// 文件: CvxText.h
//
// 说明: OpenCV汉字输出
//
// 时间:
//
// 作者: chaishushan#gmail.com
//
//====================================================================
//====================================================================
 
#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 <cv.h>
#include <highgui.h>
 
/**
* \class CvxText
* \brief OpenCV中输出汉字
*
* OpenCV中输出汉字。字库提取采用了开源的FreeFype库。由于FreeFype是
* GPL版权发布的库,和OpenCV版权并不一致,因此目前还没有合并到OpenCV
* 扩展库中。
*
* 显示汉字的时候需要一个汉字字库文件,字库文件系统一般都自带了。
* 这里采用的是一个开源的字库:“文泉驿正黑体”。
*
* 关于"OpenCV扩展库"的细节请访问
* http://code.google.com/p/opencv-extension-library/
*
* 关于FreeType的细节请访问
* http://www.freetype.org/
*
* 例子:
*
* \code
int main(int argc, char *argv[])
{
    // 定义CvxApplication对象
 
    CvxApplication app(argc, argv);
 
    // 打开一个影象
 
    IplImage *img = cvLoadImage("test.jpg", 1);
 
    // 输出汉字
 
    {
       // "wqy-zenhei.ttf"为文泉驿正黑体
 
       CvText text("wqy-zenhei.ttf");
 
       const char *msg = "在OpenCV中输出汉字!";
 
       float p = 0.5;
       text.setFont(NULL, NULL, NULL, &p);   // 透明处理
 
       text.putText(img, msg, cvPoint(100, 150), CV_RGB(255,0,0));
    }
    // 定义窗口,并显示影象
 
    CvxWindow myWin("myWin");
    myWin.showImage(img);
 
    // 进入消息循环
 
    return app.exec();
}
* \endcode
*/
 
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, float *diaphaneity=NULL);
 
    /**
     * 设置字体。目前有些参数尚不支持。
     *
     * \param font        字体类型, 目前不支持
     * \param size        字体大小/空白比例/间隔比例/旋转角度
     * \param underline   下画线
     * \param diaphaneity 透明度
     *
     * \sa getFont, restoreFont
     */
 
    void setFont( int *type,
       CvScalar *size=NULL, bool *underline=NULL, float *diaphaneity=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;
    float      m_fontDiaphaneity;
 
    //================================================================
    //================================================================
};
 
#endif // OPENCV_CVX_TEXT_2007_08_31_H

2. [代码]中文支持源文件     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#include <wchar.h>
#include <assert.h>
#include <locale.h>
#include <ctype.h>
 
#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, CvScalar *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, CvScalar *size, bool *underline, float *diaphaneity)
{
    // ²ÎÊýºÏ·¨ÐÔ¼ì²é
 
    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]);
       
       FT_Set_Pixel_Sizes(m_face, ( int )m_fontSize.val[0], 0);
    }
    if (underline)
    {
       m_fontUnderline   = *underline;
    }
    if (diaphaneity)
    {
       m_fontDiaphaneity = *diaphaneity;
    }
 
}
 
// »Ö¸´Ô­Ê¼µÄ×ÖÌåÉèÖÃ
 
void CvxText::restoreFont()
{
    m_fontType = 0;            // ×ÖÌåÀàÐÍ(²»Ö§³Ö)
 
    m_fontSize.val[0] = 25;      // ×ÖÌå´óС
    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);
}

3. [代码]实例代码     

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
 
#include "CvxText.h"
 
using namespace std;
using namespace cv;
 
#define ROW_BLOCK 2
#define COLUMN_Block 2
 
int main()
{
 
     IplImage *reDstImage = NULL; //resize image
     char pstrWindowsSrcTitle[12] = "" ;
     const char *Imagename = "11818.jpg" ;
     CvSize czSize;  //目标图像尺寸
     float p = 0.5;
     CvScalar fsize;
     
     //显示文字
     const char *msg = "你 hao" ;
     
     //读取TTF字体文件
     CvxText text( "STFANGSO.TTF" );    
     
     //设置字体属性 字体大小/空白比例/间隔比例/旋转角度
     fsize = cvScalar(200, 0.5, 0.1, 0);
     text.setFont(NULL, &fsize, NULL, &p);     
 
     //加载原图像
     IplImage* ImageSrc = cvLoadImage(Imagename, CV_LOAD_IMAGE_UNCHANGED);
     
     //设置原图像文字
     //text.putText(ImageSrc, msg, cvPoint(50, 100), CV_RGB(255,0,0));
     
     //显示原图像
     cvShowImage( "原图" , ImageSrc);
 
     //计算目标图像大小
     czSize.width = ImageSrc->width * ROW_BLOCK;
     czSize.height = ImageSrc->height * COLUMN_Block;
 
     //创建图像并缩放
     reDstImage = cvCreateImage(czSize, ImageSrc->depth, ImageSrc->nChannels);
     cvResize(ImageSrc, reDstImage, CV_INTER_AREA);
     
     //加入文字
     text.putText(reDstImage, msg, cvPoint(100, 350), CV_RGB(255,0,0));
 
     //显示放大后图像
     cvShowImage( "2" ,reDstImage);   
 
     //等待按键事件
     cvWaitKey();
 
     return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值