OpenCV2马拉松第25圈——直线拟合与RANSAC算法
2014年06月02日 19:23:31 abcd1992719g 阅读数:6461更多
所属专栏: OpenCV2马拉松
计算机视觉讨论群162501053
转载请注明:http://blog.csdn.net/abcd1992719g/article/details/28118095
收入囊中
- 最小二乘法(least square)拟合
- Total least square 拟合
- RANSAC拟合
葵花宝典
关于least square拟合,我在http://blog.csdn.net/abcd1992719g/article/details/25424061有介绍,或者看下面
最终,我们就能解出B
但是,这种least square有问题,比如针对垂直线段就不行,于是引入第二种total least square
可以参考http://www.zhihu.com/question/23998171/answer/26338148?group_id=295025143
我们可以计算得到N,解出(a,b),然后得到d.
但是误差点对least square的影响很大,如下
于是,提出了RANSAC算法
- 随机在数据集中选出小的子集(对于直线,一般选2)
- 计算得到符合这个子集合的最好模型
- 找到接近符合这个模型的数据集
- 迭代一定次数,选出最好的模型
有图有真相
或者参考这里
RANSAC用在直线拟合上,就是
Repeat N times:
•Draws points 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)
|
The function fitLine fits a line to a 2D or 3D point set by minimizing where is a distance between the point, the line and is a distance function, one of the following:
-
distType=CV_DIST_L2
-
distType=CV_DIST_L1
-
distType=CV_DIST_L12
-
distType=CV_DIST_FAIR
-
distType=CV_DIST_WELSCH
-
distType=CV_DIST_HUBER
荷枪实弹
-
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用来画出你得到的椭圆