在做目标检测时,检测到目标后,通常要用矩形框框选出目标的位置,并在旁边附上标签
在opencv实现这一目标主要用到两个函数,rectangle()
和putText()
函数原型:
void rectangle(Mat& img, Rect rec, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
void putText(Mat& img, const string& text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=8, bool bottomLeftOrigin=false )
参数详解: Mat& img:
图像数据
Rect rect:
矩形框的位置。Rect是一个class,有四个成员变量x,y,heigth,width),分别是框左上角坐标,高度,宽度。
const Scalar& color:
框线的颜色。
int thickness:
框线宽度,线占像素个数。
int lineType:
线型,默认直线。
int shift:
没看懂,官方说默认就行。
const string& text:
文本内容。
Point org:
文本左下角坐标。Point为一个class,有两个成员变量,是啥就不用我说了吧。
int fontFace:
字体类型。
double fontScale:
字体大小。
bool bottomLeftOrigin:
如果为true,文本旋转180度。
看例子:
#include <iostream>
#include <libavutil/avutil.h>
#include <opencv2/highgui.hpp>
#include <opencv4/opencv2/imgproc.hpp>
/*在视频(图像)上添加标签,本质就是画个框,再写个文本*/
using namespace cv;
using namespace std;
int main()
{
Mat image = imread("/home/lfh/图片/壁纸/老虎.jpg");
Rect rect;
rect.x = 100; //(x,y)表示左上角坐标
rect.y = 30;
rect.height = 140;
rect.width = 140;
Scalar color = CV_RGB(250,0,0); //红色
string text = "i'm tiger";
Point p; //文本框左下角坐标
p.x = rect.x;
p.y = rect.y - 5;
rectangle(image,rect,color,2);
putText(image,text,p, FONT_HERSHEY_SIMPLEX,0.6,color,1,8,0);
imshow("camera image",image);
waitKey(0);
}
结果: