问题描述
我想在cv::Mat
上放一些文字,但是cv::putText()
对我来说不够灵活.
I want to put some text on a cv::Mat
, but cv::putText()
is not flexible enough for me.
我需要在运行时已知的几个像素位置上放置可变长度的标签,但是由于cv::putText()
总是将输出的原点放在左侧,因此如果位置太远,我的文本也会消失在图像边界之外在最左边.
I need to put labels of variable length at several pixel positions which are known at runtime, but since cv::putText()
places the origin of the output always on the left, my text disappears beyond the image borders, if the position is too far on the left.
我找不到cv::putText()
的替代品.有吗?
I could not find alternatives to cv::putText()
. Are there any?
只要知道输出文本的宽度和高度(以像素为单位),我就可以自己调整位置.
It would suffice for me to know the width and height of the output text in pixels, so I could adjust the position myself.
一种更好的方法是,我可以将文本的原点指定在右侧,左侧或中间(垂直和水平).
Even better would be a method where I could specify the origin of my text to be at the right, left or middle (vertically and horizontally).
作为奖励,我想绘制带有轮廓的文本,例如具有黑色轮廓的白色字符,以便您可以在任何背景上阅读它们.
As a bonus I'd like to draw text with contours, e.g. white characters with black contours, so that you can read them on any background.
推荐答案
以下是将freetype与OpenCV一起使用的示例:
Here is the example of using freetype with OpenCV:
#include "opencv2/opencv.hpp"
#include "ft2build.h"
#include FT_FREETYPE_H
FT_Library library;
FT_Face face;
using namespace cv;
using namespace std;
//-----------------------------------------------------------------------
void my_draw_bitmap(Mat& img,FT_Bitmap* bitmap,int x,int y, Scalar color)
{
Scalar src_col,dst_col;
for(int i=0;i<bitmap->rows;i++)
{
for(int j=0;j<bitmap->width;j++)
{
unsigned char val=bitmap->buffer[j+i*bitmap->pitch];
float mix=(float)val/255.0;
if(val!=0)
{
src_col=Scalar(img.at<Vec3b>(i+y,j+x));
dst_col=mix*color+(1.0-mix)*src_col;
img.at<Vec3b>(i+y,j+x)=Vec3b(dst_col[0],dst_col[1],dst_col[2]);
}
}
}
}
//-----------------------------------------------------------------------
float PrintString(Mat& img,std::wstring str,int x,int y,Scalar color)
{
FT_Bool use_kerning=0;
FT_UInt previous=0;
use_kerning = FT_HAS_KERNING( face );
float prev_yadv=0;
float posx=0;
float posy=0;
float dx=0;
for(int k=0;k<str.length();k++)
{
int glyph_index = FT_Get_Char_Index( face, str.c_str()[k] );
FT_GlyphSlot slot = face->glyph; // a small shortcut
if(k>0){dx=slot->advance.x/64; }
FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
FT_Render_Glyph (slot,FT_RENDER_MODE_NORMAL);
prev_yadv=slot->metrics.vertAdvance/64;
if ( use_kerning && previous && glyph_index )
{
FT_Vector delta;
FT_Get_Kerning( face, previous, glyph_index, FT_KERNING_DEFAULT, &delta );
posx += (delta.x/64);
}
posx+=(dx);
my_draw_bitmap(img,&slot->bitmap,posx+x+ slot->bitmap_left,y - slot->bitmap_top+posy,color);
previous = glyph_index;
}
return prev_yadv;
}
//-----------------------------------------------------------------------
void PrintText(Mat& img,std::wstring str,int x,int y,Scalar color)
{
float posy=0;
for(int pos=str.find_first_of(L'\n');pos!=wstring::npos;pos=str.find_first_of(L'\n'))
{
std::wstring substr=str.substr(0,pos);
str.erase(0,pos+1);
posy+=PrintString(img,substr,x,y+posy, color);
}
PrintString(img,str,x,y+posy,color);
}
//-----------------------------------------------------------------------
int main(int argc, char* argv[])
{
FT_Init_FreeType( &library );
FT_New_Face( library,"arial.ttf",0,&face );
FT_Set_Pixel_Sizes(face,24,0);
FT_Select_Charmap(face, FT_ENCODING_UNICODE);
Mat img=imread("D:/ImagesForTest/lena.jpg");
std::wstring str= L"Мой дядя самых честных правил,\n\
Когда не в шутку занемог,\n\
Он уважать себя заставил \n\
И лучше выдумать не мог.\n\
Его пример другим наука;\n\
Но, боже мой, какая скука\n\
С больным сидеть и день и ночь,\n\
Не отходя ни шагу прочь!\n\
Какое низкое коварство\n\
Полу-живого забавлять,\n\
Ему подушки поправлять,\n\
Печально подносить лекарство,\n\
Вздыхать и думать про себя:\n\
Когда же чёрт возьмет тебя!\n";
PrintText(img,str,100,50,Scalar(0,255,255));
cv::imshow("win",img);
cv::waitKey(0);
return 0;
}
这篇关于比cv :: putText()更好的向ca cv :: Mat添加文本的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!