【opencv基础】Rect类的神奇用法

前言

最近看github上源码发现对两个cv::Rect使用相与(&)操作,猛地感觉自己蒙啦,Rect类还有这种神奇用法?!翻看opencv官网Rect类,果然如此!

opencv中Rect类

Rect_类有些意思,成员变量x、y、width、height,分别为左上角点的坐标和矩形的宽和高。常用的成员函数有Size()返回值为一个Size,area()返回矩形的面积,contains(Point)用来判断点是否在矩形内,inside(Rect)函数判断矩形是否在该矩形内,tl()返回左上角点坐标,br()返回右下角点坐标。

Rect类的使用

  • rect = rect ± point (shifting a rectangle by a certain offset)
  • rect = rect ± size (expanding or shrinking a rectangle by a certain amount)
  • rect += point, rect -= point, rect += size, rect -= size (augmenting operations)
  • rect = rect1 & rect2 (rectangle intersection)
  • rect = rect1 | rect2 (minimum area rectangle containing rect1 and rect2 )
  • rect &= rect1, rect |= rect1 (and the corresponding augmenting operations)
  • rect == rect1, rect != rect1 (rectangle comparison)

两个矩形的交并

Rect rect = rect1 & rect2;
Rect rect = rect1 | rect2;

两个矩形的平移或者缩放

Rect rectShift = rect + point;
Rect rectScale = rect + size;

all usage

//如果创建一个Rect对象rect(100, 50, 50, 100),那么rect会有以下几个功能:
rect.area(); //返回rect的面积 5000
rect.size(); //返回rect的尺寸 [50 × 100]
rect.tl(); //返回rect的左上顶点的坐标 [100, 50]
rect.br(); //返回rect的右下顶点的坐标 [150, 150]
rect.width(); //返回rect的宽度 50
rect.height(); //返回rect的高度 100
rect.contains(Point(x, y)); //返回布尔变量,判断rect是否包含Point(x, y)点 //还可以求两个矩形的交集和并集
rect = rect1 & rect2;
rect = rect1 | rect2; //还可以对矩形进行平移和缩放
rect = rect + Point(-, ); //平移,也就是左上顶点的x坐标-100,y坐标+100
rect = rect + Size(-, ); //缩放,左上顶点不变,宽度-100,高度+100 //还可以对矩形进行对比,返回布尔变量
rect1 == rect2;
rect1 != rect2; //OpenCV里貌似没有判断rect1是否在rect2里面的功能,所以自己写一个吧
bool isInside(Rect rect1, Rect rect2)
{
return (rect1 == (rect1&rect2));
} //OpenCV貌似也没有获取矩形中心点的功能,还是自己写一个
Point getCenterPoint(Rect rect)
{
Point cpt;
cpt.x = rect.x + cvRound(rect.width/2.0);
cpt.y = rect.y + cvRound(rect.height/2.0);
return cpt;
} //围绕矩形中心缩放
Rect rectCenterScale(Rect rect, Size size)
{
rect = rect + size;
Point pt;
pt.x = cvRound(size.width/2.0);
pt.y = cvRound(size.height/2.0);
return (rect-pt);
}

参考

1.opencv官网Rect类

2.opencv中的Rect类

2.opencv中Rect类用法

3.opencv中Rect类的神奇用法

上一篇:xilinx planahead partial reconfiguration


下一篇:SQL Server 快捷键备忘