RotatedRect该类表示平面上的旋转矩形,有三个属性:

  1. 矩形中心点(质心)
  2. 边长(长和宽)
  3. 旋转角度

 1 class CV_EXPORTS RotatedRect
 2 {
 3 public:
 4     //构造函数
 5     RotatedRect();
 6     RotatedRect(const Point2f& center, const Size2f& size, float angle);
 7     RotatedRect(const CvBox2D& box);
 8     void points(Point2f pts[]) const;//!返回矩形的4个顶点
 9     Rect boundingRect() const; //返回包含旋转矩形的最小矩形
10     operator CvBox2D() const;    //!转换到旧式的cvbox2d结构
11     Point2f center; //矩形的质心
12     Size2f size;   //矩形的边长
13     float angle;  //旋转角度,当角度为0、90、180、270等时,矩形就成了一个直立的矩形
14 };

        这个类中包含了外接矩形的中心center、大小size以及角度angle。为了更好的理解这几个参数的意义,请看下图:在opencv中,坐标的原点在左上角,与x轴平行的方向为角度为0,逆时针旋转角度为负,顺时针旋转角度为正。角度是水平轴(x轴)顺时针旋转,与碰到的第一个边的夹角度数。而opencv默认把这个边的边长作为height。

 

 1 #include<opencv2/opencv.hpp>
 2 #include<iostream>
 3 using namespace std;
 4 using namespace cv;
 5 
 6 int main()
 7 {
 8     Mat img = imread("C:\\Users\\hsy\\Desktop\\1.jpg");
 9     Mat img_gray;
10     cvtColor(img, img_gray, COLOR_RGB2GRAY);
11     img_gray = img_gray > 30;
12     vector<vector<Point>>contours;
13     vector<Vec4i> hierarchy;
14     vector<RotatedRect>rect;
15     //【5】查找轮廓
16     findContours(img_gray, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
17     for (int i = 0; i < contours.size(); i++)
18     {
19         rect.push_back(minAreaRect(contours[i]));
20         Point2f vertices[4];      //定义矩形的4个顶点
21         rect[i].points(vertices);   //计算矩形的4个顶点
22         for (int i = 0; i < 4; i++)
23             line(img, vertices[i], vertices[(i + 1) % 4], Scalar(0, 255, 0),1);
24         cout <<"width的值:"<<rect[i].size.width << endl;
25         cout << "height的值:" << rect[i].size.height << endl;//其实只有一个外接矩形
26     }
27     imshow("img", img);
28     waitKey(0);
}