【问题标题】:Calculate text size计算文本大小
【发布时间】:2018-10-25 12:06:56
【问题描述】:

注意:这个问题How to put text into a bounding box in OpenCV? 在某些方面与这个问题相似,但不是同一个问题。问题的 OP 试图将文本传播到他的图像的整个大小,并且得到标记的答案中的代码只是使用蒙版调整文本的大小。

我正在使用openCV 结合C++ 进行一些图像检测和处理。

所以我想在特定原点对齐具有 未知长度 的文本。应该计算字体比例,因为我想为最大文本宽度指定一个宽度因子,如下图所示:

这是我目前得到的代码:

int fontFace = cv::FONT_HERSHEY_DUPLEX,
    fontScale = myTextString.size() / 10;

cv::Size textSize = getTextSize(image, fontFace, fontScale, 0, 0);
putText(image, myTextString, cv::Point( (origin.x + textSize.width)/2, (origin.y + textSize.height)/2 ), fontFace, fontScale, Scalar(255, 0, 0));

【问题讨论】:

  • 问题:如何实现一个函数来计算与文本长度相关的最大宽度的文本的比例因子? | 问题:真的不知道如何解决这个问题。
  • 所以你想选择一个fontScale 使得textWidth 不超过maximumWidth。对吗?
  • 你做对了 :) @zindarod
  • 你见过this answer吗?
  • Python 图像库版本 vs openCV。我认为你混淆了一些东西:) @zindarod

标签: c++ image opencv image-processing


【解决方案1】:

这样的事情应该可以做到。您可以更改边距的计算方式以更改字体的水平/垂直对齐方式。

如果高度无关紧要,你可以留下target.height一个很大的数字。

void drawtorect(cv::Mat & mat, cv::Rect target, int face, int thickness, cv::Scalar color, const std::string & str)
{
    cv::Size rect = cv::getTextSize(str, face, 1.0, thickness, 0);
    double scalex = (double)target.width / (double)rect.width;
    double scaley = (double)target.height / (double)rect.height;
    double scale = std::min(scalex, scaley);
    int marginx = scale == scalex ? 0 : (int)((double)target.width * (scalex - scale) / scalex * 0.5);
    int marginy = scale == scaley ? 0 : (int)((double)target.height * (scaley - scale) / scaley * 0.5);
    cv::putText(mat, str, cv::Point(target.x + marginx, target.y + target.height - marginy), face, scale, color, thickness, 8, false);
}

* 编辑 *

// Sample code
int L = 80; // width and height per square
int M = 60;
cv::Mat m( 5*M, 7*L,CV_8UC3,cv::Scalar(0,0,0) );
// create checkerboard
for ( int y=0,ymax=m.rows-M;y<=ymax; y+=M)
{
    int c = (y/M)%2 == 0 ? 0 : 1;
    for ( int x=0,xmax=m.cols-L;x<=xmax;x+=L)
    {
        if ( (c++)%2!=0 )
            continue; // skip odd squares
        // convenient way to do this
        m( cv::Rect(x,y,L,M) ).setTo( cv::Scalar(64,64,64) );
    }
}
// fill checkerboard ROIs by some text
int64 id=1;
for ( int y=0,ymax=m.rows-M;y<=ymax; y+=M)
{
    for ( int x=0,xmax=m.cols-L;x<=xmax;x+=L)
    {
        std::stringstream ss;
        ss<<(id<<=1); // some increasing text input
        drawtorect( m, cv::Rect(x,y,L,M), cv::FONT_HERSHEY_PLAIN,1,cv::Scalar(255,255,255),ss.str() );
    }
}

【讨论】:

  • 感谢您提供紧凑型解决方案,但您介意添加用于已添加图像的代码吗? :)
  • @jonas00 ,添加:)
猜你喜欢
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多