首页 > 技术文章 > OpencV使用fitEllipse拟合椭圆后,获取椭圆参数 【转载】

qiushui127 2017-08-03 14:42 原文

以下内容来自:http://blog.csdn.net/sinat_31425585/article/details/75103239

(申明:纯属资料收藏,望作者看到后谅解!)

使用OpenCV的fitEllipse函数拟合椭圆后,会得到一个RotatedRect类型的返还值,首先介绍一下RotatedRect结构,这个参考的无左无右的博客:点击打开链接,嫌左右跳麻烦,所以直接贴过来

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

 

     需要注意的是angle对应角度是角度,如果使用三角函数sin,cos,tan之类的需要先转换成弧度,boundingRect对应水平方向外接矩形而不是椭圆的外接矩形,如果需要获取椭圆的两个半轴长度可以通过size.width和size.height得到,其余的参数看一下上面代码对应注释.

     下面就是怎么通过一个RotatedRect来获取椭圆参数,具体原理可以参考百度文库的一个文档:点击打开链接,直接截图看一下:



因为这里默认的是顺时针旋转为正,而图像里面默认是逆时针旋转为正,只需要把B乘以一个负号就行,感兴趣的同学自己推导一下.

好了,到了上代码的时间了,代码如下:

  1. #include <opencv2//opencv.hpp>  
  2. #include <iostream>  
  3. #include <math.h>  
  4.   
  5.   
  6. using namespace cv;  
  7. using namespace std;  
  8.   
  9.   
  10. struct EllipsePara  
  11. {  
  12.     Point2f c;  
  13.     float A;  
  14.     float B;  
  15.     float C;  
  16.     float F;  
  17. };  
  1. void getEllipsePara(RotatedRect & ellipsemege, EllipsePara& EP_t)  
  2. {  
  3.       
  4.   
  5.     float theta = ellipsemege.angle * CV_PI / 180.0 ;  
  6.     float a = ellipsemege.size.width / 2.0;  
  7.     float b = ellipsemege.size.height / 2.0;  
  8.   
  9.     EP_t.c.x = ellipsemege.center.x;  
  10.     EP_t.c.y = ellipsemege.center.y;  
  11.   
  12.     EP_t.A = a * a * sin(theta) * sin(theta) + b * b * cos(theta) * cos(theta);  
  13.     EP_t.B = (-2.0) * (a * a - b * b) * sin(theta) * cos(theta);  
  14.     EP_t.C = a * a * cos(theta) * cos(theta) + b * b * sin(theta) * sin(theta);  
  15.     EP_t.F = (-1.0) * a * a * b * b;  
  16.   
  17.   
  18.     //cout << "theta: " << theta << " x: " << EP.c.x << " y: " << EP.c.y << " C: " << EP.C << " F: " << EP.F << endl;  
  19.   
  20.   
  21. }  
  22. void main()  
  23. {  
  24.     //RotatedRect(const Point2f& center, const Size2f& size, float angle);    
  25.     RotatedRect Rec_t = RotatedRect(Point2f(0,0), Size2f(4,1), 90);  
  26.     cout << Rec_t.size.width << " " << Rec_t.size.height << endl;  
  27.   
  28.     cout << Rec_t.boundingRect().width <<  " " << Rec_t.boundingRect().height <<  endl;  
  29.     EllipsePara EP_t;  
  30.     getEllipsePara(Rec_t, EP_t);  
  31.   
  32.     cout << EP_t.A << " " << EP_t.B << " " << EP_t.C << " " << EP_t.F << endl;  
  33.       
  34.       
  35.   
  36.   
  37. }  

得到的椭圆方程为:


打完收工!!!

 

推荐阅读