Opencv中使用Rect的函数创建按钮和文字

#include <opencv\highgui.h>
#include<opencv\cxcore.h>
#include <opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
Mat img;
Rect drawString(Mat img, string text, Point coord, Scalar color, float fontScale = 0.6f, int thickness = 1, int fontFace = FONT_HERSHEY_COMPLEX)
{
//获取文本大小和基线 
int baseline = 0;
Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline);
baseline += thickness;
// 为左/右或上/下调整校正坐标
if (coord.y >= 0) {
//图像左上角的文本的左上角的坐标,因此按行向下移动
coord.y += textSize.height;
}
else {
//图像左下角的文本的左下角的坐标,因此从底部上来
coord.y += img.rows - baseline + 1;
}
// 如果希望变成右侧调整
if (coord.x < 0) {
coord.x += img.cols - textSize.width + 1;
}


// 获取文本的边界矩形
Rect boundingRect = Rect(coord.x, coord.y - textSize.height, textSize.width, baseline + textSize.height);


// 画出平滑的文本
putText(img, text, coord, fontFace, fontScale, color, thickness, CV_AA);


//让用户知道文本的多大,以防他们想安排些事情
return boundingRect;
}
Rect drawButton(Mat img, string text, Point coord, int minWidth = 0)
{
int B = 10;
Point textCoord = Point(coord.x + B, coord.y + B);
// 获取文本边界矩形
Rect rcText = drawString(img, text, textCoord, CV_RGB(0, 0, 0));
// 在文本周围画一个填充的矩形
Rect rcButton = Rect(rcText.x - B, rcText.y - B, rcText.width + 2 * B, rcText.height + 2 * B);
// 设置按钮的最小宽度
if (rcButton.width < minWidth)
rcButton.width = minWidth;
// 创建一个半透膜的白色矩形
Mat matButton = img(rcButton);
matButton += CV_RGB(90, 90, 90);
//画一个非透明的白色边界 
rectangle(img, rcButton, CV_RGB(200, 200, 200), 1, CV_AA);


//使用抗锯齿,画一个实际用来显示的文本
drawString(img, text, textCoord, CV_RGB(10, 55, 20));


return rcButton;
}


void main()
{
img = imread("C:\\Users\\hasee\\Desktop\\cat2.jpg");
const int b = 10;
string str = "This is a cat";
string btn_name1 = "button01";
string btn_name2 = "button02";
string btn_name3 = "button03";
Rect btn01;
Rect btn02;
Rect btn03;
drawString(img,str,Point(20,-20),Scalar(123,21,211),0.55f,1,3);
btn01 = drawButton(img,btn_name1,Point(b,b),0);
btn02 = drawButton(img, btn_name2, Point(btn01.x, btn01.height+b), btn01.width);
btn03 = drawButton(img, btn_name3, Point(btn01.x, btn02.height+btn02.y), btn01.width);
imshow("123", img);


waitKey(0);


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值