OpenCV绘图函数(11)计算文本字符串在特定字体、尺寸和厚度下的大小的函数getTextSize()的使用

  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

计算一个文本字符串的宽度和高度。
函数 cv::getTextSize 计算并返回包含指定文本的矩形框的尺寸。也就是说,下面的代码渲染一些文本、包围它的紧密矩形框以及基线:

String text = "Funny text inside the box";
int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX;
double fontScale = 2;
int thickness = 3;
Mat img(600, 800, CV_8UC3, Scalar::all(0));
int baseline=0;
Size textSize = getTextSize(text, fontFace,
                            fontScale, thickness, &baseline);
baseline += thickness;
// center the text
Point textOrg((img.cols - textSize.width)/2,
              (img.rows + textSize.height)/2);
// draw the box
rectangle(img, textOrg + Point(0, baseline),
          textOrg + Point(textSize.width, -textSize.height),
          Scalar(0,0,255));
// ... and the baseline first
line(img, textOrg + Point(0, thickness),
     textOrg + Point(textSize.width, thickness),
     Scalar(0, 0, 255));
// then put the text itself
putText(img, text, textOrg, fontFace, fontScale,
        Scalar::all(255), thickness, 8);

函数原型


Size cv::getTextSize
(
	const String & 	text,
	int 	fontFace,
	double 	fontScale,
	int 	thickness,
	int * 	baseLine 
)		

参数

  • 参数text 输入的文本字符串。
  • 参数fontFace 要使用的字体,参见 HersheyFonts。
  • 参数fontScale 字体缩放因子,乘以特定字体的基本尺寸。
  • 参数thickness 用于渲染文本的线条厚度。详情请参阅 putText。
  • 参数[out] baseLine 相对于文本最底部点的基线 y 坐标。

代码示例

该示例展示了如何计算文本字符串的宽度和高度,并在图像上绘制文本及其周围的紧致矩形框和基线。

#include 
#include 

int main()
{
    // 定义文本和字体参数
    std::string text = "Sample Text";
    int fontFace     = cv::FONT_HERSHEY_SIMPLEX;
    double fontScale = 1.0;
    int thickness    = 2;

    // 获取文本尺寸
    cv::Size text_size;
    int baseline = 0;
    text_size    = cv::getTextSize( text, fontFace, fontScale, thickness, &baseline );

    // 输出文本尺寸
    std::cout << "Text Size: " << text_size.width << " x " << text_size.height << std::endl;

    // 创建一个白色背景的图像
    cv::Mat image( 100, 400, CV_8UC3, cv::Scalar( 255, 255, 255 ) );

    // 定义文本起始位置
    cv::Point textOrg( 10, 50 + baseline );  // 文本起始位置

    // 在图像上绘制文本
    cv::putText( image, text, textOrg, fontFace, fontScale, cv::Scalar( 0, 0, 0 ), thickness );

    // 调整矩形框的坐标以确保它从文本的顶部开始,到底部结束
    cv::Point rectTopLeft( textOrg.x, textOrg.y - text_size.height );
    cv::Point rectBottomRight( textOrg.x + text_size.width, textOrg.y + baseline );

    // 绘制紧致矩形框
    cv::rectangle( image, rectTopLeft, rectBottomRight, cv::Scalar( 0, 255, 0 ), 1 );

    // 绘制基线
    cv::line( image, textOrg, cv::Point( textOrg.x + text_size.width, textOrg.y ), cv::Scalar( 0, 0, 255 ) );

    // 显示图像
    cv::imshow( "Text Sample", image );
    cv::waitKey( 0 );

    return 0;
}

运行结果

OpenCV绘图函数(11)计算文本字符串在特定字体、尺寸和厚度下的大小的函数getTextSize()的使用_第1张图片

你可能感兴趣的:(OpenCV,opencv,webpack,人工智能)