1.Rect类
创建类
Rect类成员变量x、y、width、height,分别为左上角点的坐标和矩形的宽和高。
创建一个Rect对象Rect,并在图像上画该矩形框。
cv::Rect rect(100, 50, 500, 500);
cv::Mat cv_src = cv::imread("11.JPG");
cv::rectangle(cv_src, rect, cv::Scalar(255, 0, 0),4);
cv::namedWindow("src", 0);
cv::imshow("src", cv_src);
cv::waitKey(0);
2. Rect常用参数
cv::Rect rect(100, 50, 500, 500);
rect.area();//面积
rect.size();//大小
rect.tl(); //左上角
rect.br(); //右下角
rect.size().width;//宽
rect.size().height; //高
std::cout << "rect area = " << rect.area() << ",rect size = " << rect.size()
<< ",rect tl = " << rect.tl() << ",rect br = " << rect.br() << ", rect width = "
<< rect.size().width << ",rect height = " << rect.size().height << std::endl;
输出
rect area = 250000,rect size = [500 x 500],rect tl = [100, 50],rect br = [600, 550], rect width = 500,rect height = 500
3. 常用判断
3.1 判断点是否在矩形内,就是矩形是否包含这个点
rect.contains(cv::Point(x, y));
3.2 判断对比两个矩形是否相等
rect1 == rect2;
rect1 != rect2;
3.3 判断矩形是否包含另一个矩形
bool isInside(cv::Rect& rect1, cv::Rect& rect2)
{
if (rect1.area() > rect2.area())
{
return (rect1 == (rect1 & rect2));
}
else
{
return (rect2 == (rect2 & rect1));
}
}
测试调用代码
cv::Rect rect1(100, 50, 500, 500);
cv::Rect rect2(150, 100, 300, 300);
cv::Mat cv_src = cv::imread("11.JPG");
cv::rectangle(cv_src, rect1, cv::Scalar(255, 0, 0),4);
cv::rectangle(cv_src, rect2, cv::Scalar(255, 0, 255), 4);
cv::namedWindow("src", 0);
cv::imshow("src", cv_src);
std::cout << isInside(rect1, rect2) << std::endl;
cv::waitKey(0);
3.4 判断两个矩形是否相交
当要判断两具矩形是否相交,就要考虑到,两个矩形如果相交几种可能性。
bool computRectJoinUnion(cv::Rect& r1, cv::Rect& r2)
{
if (r1.area() > r2.area())
{
if (r1.contains(r2.tl()) || r1.contains(r2.br()))
{
return true;
}
else
{
return false;
}
}
else if (r1.area() < r2.area())
{
if (r2.contains(r1.tl()) || r2.contains(r1.br()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
4.矩形常用操作
4.1 获取矩形矩形中心
cv::Point getCenterPoint(cv::Rect& rect)
{
cv::Point cpt;
cpt.x = rect.x + cvRound(rect.width/2.0);
cpt.y = rect.y + cvRound(rect.height/2.0);
return cpt;
}
4.2 缩放矩形
//缩放矩形
cv::Rect rectScale(cv::Rect& rect, float x_scale, float y_scale)
{
cv::Rect cv_rect;
cv_rect.x = rect.x * x_scale;
cv_rect.y = rect.y * y_scale;
cv_rect.width = rect.width * x_scale;
cv_rect.height = rect.height * y_scale;
return cv_rect;
}