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);
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
rect.contains(cv::Point(x, y));
rect1 == rect2;
rect1 != rect2;
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);
当要判断两具矩形是否相交,就要考虑到,两个矩形如果相交几种可能性。
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;
}
}
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;
}
//缩放矩形
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;
}