OpenCV2马拉松第25圈——直线拟合与RANSAC算法

计算机视觉讨论群162501053


收入囊中
  • 最小二乘法(least square)拟合
  • Total least square 拟合
  • RANSAC拟合

葵花宝典

关于least square拟合,我在http://blog.csdn.net/abcd1992719g/article/details/25424061有介绍,或者看以下


终于,我们就能解出B


可是。这样的least square有问题,比方针对垂直线段就不行。于是引入另外一种total least square



我们能够计算得到N,解出(a,b),然后得到d.


可是误差点对least square的影响非常大。例如以下




于是,提出了RANSAC算法
  1. 随机在数据集中选出小的子集(对于直线,一般选2)
  2. 计算得到符合这个子集合的最好模型
  3. 找到接近符合这个模型的数据集
  4. 迭代一定次数,选出最好的模型
有图有真相



或者參考这里

RANSAC用在直线拟合上。就是

Repeat times:

    •Drawpoints uniformly at random
    •Fit line to theses points
    •Find inliers to this line among the remaining points(i.e., points whose distance from the line is less thant)
    •If there ared or more inliers, accept the line and refit using all inliers(refit的意思就是:我们迭代后找到了一条最好直线,如果有200个接近点。那么就用这200个点再进行least square又一次拟合下)


RANSAC是一个概率算法,迭代次数越多越准确

Pros
简单通用
能够解决非常多问题
实践有效
Cons
须要确定一系列參数
有时候须要迭代次数多。概率算法有时候会失败
最小样本数无法得到有效模型


初识API

OpenCV提供了一个拟合直线的方法。能够拟合2维和3维空间的直线
C++: void fitLine(InputArray points, OutputArray line, int distType, double param, double reps, double aeps)
 
  • points – 2D或者3D点的输入向量。存储在std::vector<> 或者 Mat中.
  • line –2D来说 (就像Vec4f) - (vx, vy, x0, y0),(vx, vy)是归一化直线方向,(x0, y0)是直线上的一个点. 对于3D的拟合 (就如 Vec6f) - (vx, vy, vz, x0, y0, z0),
  • distType – 例如以下
  • param – 一般取0
  • reps – 一般取0.01
  • aeps – 一般取0.01

The function fitLine fits a line to a 2D or 3D point set by minimizing sum_i 
ho(r_i) where r_i is a distance between the i^{th} point, the line and 
ho(r) is a distance function, one of the following:

  • distType=CV_DIST_L2

    
ho (r) = r^2/2  quad 	ext{(the simplest and the fastest least-squares method)}

  • distType=CV_DIST_L1

    
ho (r) = r

  • distType=CV_DIST_L12

    
ho (r) = 2  cdot ( sqrt{1 + frac{r^2}{2}} - 1)

  • distType=CV_DIST_FAIR

    
ho left (r 
ight ) = C^2  cdot left (  frac{r}{C} -  log{left(1 + frac{r}{C}
ight)} 
ight )  quad 	ext{where} quad C=1.3998

  • distType=CV_DIST_WELSCH

    
ho left (r 
ight ) =  frac{C^2}{2} cdot left ( 1 -  exp{left(-left(frac{r}{C}
ight)^2
ight)} 
ight )  quad 	ext{where} quad C=2.9846

  • distType=CV_DIST_HUBER

    
ho (r) =  fork{r^2/2}{if $r < C$}{C cdot (r-C/2)}{otherwise} quad 	ext{where} quad C=1.345




荷枪实弹


cv::Vec4f line;
cv::fitLine(cv::Mat(points),line,CV_DIST_L2, 0, 0.01,0.01);
这样调用,就能够得到我们的直线參数


举一反三

 cv::fitEllipse 在一系列2D点中拟合椭圆. 它返回一个旋转过的矩形 (一个cv::RotatedRect实例),椭圆内切于这个矩形. 你能够书写例如以下代码:

cv::RotatedRect rrect= cv::fitEllipse(cv::Mat(points));
cv::ellipse(image,rrect,cv::Scalar(0));

函数cv::ellipse用来画出你得到的椭圆



原文地址:https://www.cnblogs.com/slgkaifa/p/7128316.html