OpenCV4入门教程006:Rect()

索引地址:系列索引

Rect()

一个矩形对象,是一个面,面由点组成。最基本的包括x,y,width,height,即在x轴起点(一般为0)y轴起点(一般为0)宽度和高度。

此对象还有面积,是否包含点等。

函数原型:

1
typedef Rect_<int> Rect;

也就是说Rect()是用int类型实例化的Rect_,那么我们具体看一下Rect_的函数原型。

1
2
3
4
5
6
Rect_();//形参列表为空,即定义一个空窗口(默认值为:x=y=width=height=0);
Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);//定义一个左上角点坐标为(_x, _y)的_width*_height矩形窗口;
Rect_(const Rect_& r);//使用其他的Rect_对象初始化;
Rect_(const CvRect& r);//使用CvRect对象初始化;
Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);//分别将位置坐标(_x, _y)和窗口大小(_width, _height)用Point_和Size_对象初始化;
Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);//分别将坐标位置(_x, _y)和窗口大小(_width, _height)用Point_和Point_对象初始化。

就是一个面最基本的,左上角x,y的起始点,然后是宽度和高度。可以用于指定上图中的黑色方框。也就是说,可以用于获取一张图片中某个子图片。

CvRect和Rect有什么区别呢?没什么区别,CvRect是C的函数,Rect是C++。

以下是Rect的常用用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <opencv2/opencv.hpp>
#include <vector>

using namespace std;
using namespace cv;

int main() {
Mat image = imread("lena.jpg");
Rect rect1(256, 256, 128, 128);
Rect rect2(224, 224, 128, 128);

Mat roi1;
image(rect1).copyTo(roi1); // 将image中rect1的部分复制到roi1中
imshow("1", roi1);
waitKey(0);

Mat roi2;
image(rect2).copyTo(roi2); // 将image中rect2复制到roi2中
imshow("2", roi2);
waitKey(0);

cv::Rect rect3 = rect1 & rect2; // rect1和rect2的交集
Mat roi3;
image(rect3).copyTo(roi3);
imshow("3", roi3);
waitKey(0);

Rect rect4 = rect1 | rect2; // rect1和rect2的并集(两幅图的最小外接矩形)
Mat roi4;
image(rect4).copyTo(roi4);
imshow("4", roi4);
waitKey(0);

Rect rect5(10, 10, 128, 128);
roi1.copyTo(image(rect5)); // 将rect1复制到image的指定区域rect5中
imshow("5", image);
waitKey(0);
}

测试效果如图:

rect

两幅图像的&|操作之后在介绍。


OpenCV4入门教程006:Rect()
https://feater.top/opencv/opencv-useful-class-rect/
作者
JackeyLea
发布于
2020年5月12日
许可协议