4.5 文字绘制

这段代码演示了如何在OpenCV中使用PutText函数在图像上添加文本,涉及字体选择、尺寸调整和文本定位。
摘要由CSDN通过智能技术生成

PutText 函数在图像中呈现指定的文本字符串。不能使用指定字体呈现的符号将由问号替换。

void cv::putText	(	
cv::Mat & img,//待绘制的图像
const String & 	text,//待绘制的文字
Point 	org,//文本框的左下角
int 	fontFace,//字体类型
double 	fontScale,//尺寸因子,值越大,文字就越大
Scalar 	color,//线条颜色 RGB
int 	thickness = 1,//线条宽度
int 	lineType = LINE_8,//线型  4领域或8领域,默认为8领域
bool 	bottomLeftOrigin = false //如果为 true,则图像数据原点位于左下角,否则位于左上角。
)

getTextSize()用于获取字符串的宽度和高度。函数的返回包含文本框的大小。

Size cv::getTextSize	
(const String & 	text,   //输入文本字符串。
int 	fontFace,//要使用的字体,请参阅 HersheyFonts。
double 	fontScale,//字体缩放因子,乘以特定于字体的基本大小。
int 	thickness,//用于呈现文本的行的厚度。有关详细信息,请参见 putText
int * 	baseLine //基线相对于最底部文本点的 y 坐标。
)

代码

#include "pch.h"
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include<opencv2\imgproc.hpp>
//#pragma comment(lib, "opencv_world450d.lib")  //引用引入库 
using namespace std;
using namespace cv;

int main()
{
	string text = "I am a student studying Opencv";//Funny text inside the box
	//int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX;     //手写风格字体
	int fontFace = FONT_HERSHEY_SCRIPT_COMPLEX;
	double fontScale = 2;       //字体缩放比
	int thickness = 3;

	Mat img(600, 1000, 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));
	line(img, textOrg + Point(0, thickness), textOrg + Point(textSize.width, thickness), Scalar(0, 0, 255));
	putText(img, text, textOrg, fontFace, fontScale, Scalar::all(255), thickness, 8);
	imshow("text", img);
	waitKey(0);
	return 0;
}

运行结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值