一.cv::Rect类
(1)基本概念
cv::Rect类(矩形类)包括cv::Point类的成员x和y(用来表示矩形左上角顶点的坐标)以及cv::Size类的成员width和height(用来表示矩形的宽和高),其主要用来表示一个二维的矩形。在Opencv中其定义如下:
template<typename _Tp> class Rect_
{
public:
typedef _Tp value_type;
//! default constructor
Rect_();
Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
Rect_(const Rect_& r);
Rect_(Rect_&& r) CV_NOEXCEPT;
Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);
Rect_& operator = ( const Rect_& r );
Rect_& operator = ( Rect_&& r ) CV_NOEXCEPT;
//! the top-left corner
Point_<_Tp> tl() const;
//! the bottom-right corner
Point_<_Tp> br() const;
//! size (width, height) of the rectangle
Size_<_Tp> size() const;
//! area (width*height) of the rectangle
_Tp area() const;
//! true if empty
bool empty() const;
//! conversion to another data type
template<typename _Tp2> operator Rect_<_Tp2>() const;
//! checks whether the rectangle contains the point
bool contains(const Point_<_Tp>& pt) const;
_Tp x; //!< x coordinate of the top-left corner
_Tp y; //!< y coordinate of the top-left corner
_Tp width; //!< width of the rectangle
_Tp height; //!< height of the rectangle
};
typedef Rect_<int> Rect2i;
typedef Rect_<float> Rect2f;
typedef Rect_<double> Rect2d;
typedef Rect2i Rect;
需要注意的是,cv::Rect类同样是cv::Rect_类int类型的别名,此外,别名还有Rect2f,Rect2d,分别用来表示float与double类型.
(2)用法
1.cv::Rect类支持的构造方式有以下几种:
cv::Rect r;//默认构造
cv::Rect r1(3, 4, 5, 6);//赋值构造
cv::Rect r2(r1);//通过拷贝构造
cv::Point p(1, 3);
cv::Size s(2, 4);
cv::Rect r3(p, s);//通过设置顶点与长宽构造
cv::Point p1(3, 7);
cv::Rect r4(p, p1);//通过设置左上角与右下角顶点构造
2.矩形类的成员可以通过命名变量访问,此外,其还支持各种重载运算符,可用于计算两个矩形或一个矩形和另一个对象的各种集合属性,具体操作可参考以下示例:
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main()
{
Mat I=Mat::zeros(300, 400, CV_8UC3);//创建一个黑色的幕布,大小为300*400
Rect r1(10, 10, 100, 200);
Rect r2(50, 60, 200, 150);
rectangle(I, r1, Scalar(0, 255, 0), 2);//将矩r1画在幕布上,颜色为绿色,矩形边线厚度为2
rectangle(I, r2, Scalar(0, 0, 255), 2);
imshow("rectangle", I);//显示
waitKey(1000);//1000ms刷新一次
Mat B = I.clone();
//求交集
Rect r3 = r1 & r2;
rectangle(B, r3, Scalar(255, 0, 0), 2); //将矩r3画在幕布B上,颜色为蓝色,矩形边线厚度为2
imshow("交集", B);
waitKey(1000);
//两个矩形的并集
B = I.clone();
Rect r4 = r1 | r2;
rectangle(B, r4, Scalar(255, 0, 0), 2);
imshow("并集", B);
waitKey(1000);
//改变矩形大小
B = I.clone();
Rect r5(r1);
r4 += Size(50, 60);//将r4长宽各增加50,60
rectangle(B, r5, Scalar(255, 0, 0), 2);
imshow("enlarge", B);
waitKey(1000);
//平移矩形
B = I.clone();
Rect r6(r1);
r6 += Point(60, 60);//将左上顶点平移
rectangle(B, r6, Scalar(255, 0, 0), 2);
imshow("translate", B);
waitKey();
//
Point p(250, 100);
cout << "rectangle r1" << r1 << endl;
cout << "is r1=r2" << (r1 == r2) << endl;
cout << "is r1 contains p" << r1.contains(p) << endl;//判断点p是否在矩形r1中
}
运行结果如下:
屏幕输出如下:
附: