请解释cv::Rect
时间: 2023-07-30 12:11:49 浏览: 43
`cv::Rect`是OpenCV中用于表示矩形区域的类。它的定义如下:
```c++
class CV_EXPORTS Rect
{
public:
//! default constructor
Rect();
//! constructor from two points
Rect(Point pt1, Point pt2);
//! constructor from (x,y) and (width,height)
Rect(int x, int y, int width, int height);
//! returns the rectangle area
double area() const;
//! returns the minimal rectangle containing the current rectangle and the given rectangle
Rect operator | (const Rect& r) const;
//! returns the intersection of two rectangles
Rect operator & (const Rect& r) const;
//! returns the rectangle shifted by (dx,dy)
Rect operator + (Point pt) const;
//! returns the rectangle scaled by (fx,fy)
Rect operator * (double f) const;
//! checks whether the rectangle contains the point
bool contains(Point pt) const;
int x, y, width, height; //< the top-left corner, and width and height of the rectangle
};
```
其中,`x`和`y`表示矩形左上角的坐标,`width`和`height`表示矩形的宽度和高度。`Rect`类提供了一些常用的操作,比如计算矩形的面积、返回两个矩形的交集或并集、移动或缩放矩形等。在OpenCV中,矩形区域常用于表示图像中的ROI(Region of Interest)。
下面是一个简单的例子,演示如何使用`cv::Rect`来提取图像的ROI:
```c++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 加载图像
Mat image = imread("test.jpg");
// 定义ROI区域
Rect roi(100, 100, 200, 200);
// 提取ROI区域
Mat roi_image = image(roi);
// 显示原图和ROI图像
imshow("Original", image);
imshow("ROI", roi_image);
waitKey(0);
return 0;
}
```
这个例子会加载一张图片,然后定义一个矩形ROI区域,最后通过`image(roi)`提取ROI图像并显示出来。