In OpenCv, it only provide the function fitEllipse to fit Ellipse, but doesn't provide function to fit circle, so i read some paper, and write a function to do it. The paper it refer to is "A Few Methods for Fitting Circles to Data".

Also when there is a lot of noise in the data, need to find a way to exclude the noise data and get a more accuracy result.

There are two methods, one is iterate method, first use all the data to fit a model, then find the points exceed the error tolerance to the model, excude them and fit again. Until reach iteration times limit or all the data is in error tolerance.

Another method is ransac method, it has detailed introduction in paper "Random Sample Consensus: A Paradigm for Model Fitting with Apphcatlons to Image Analysis and Automated Cartography".

// This function is based on Modified Least Square Methods from Paper
// "A Few Methods for Fitting Circles to Data".
cv::RotatedRect FitCircle(const std::vector<cv::Point2f> &vecPoints)
{
cv::RotatedRect rotatedRect;
if ( vecPoints.size() < )
return rotatedRect; double Sx = ., Sy = ., Sx2 = ., Sy2 = ., Sxy = ., Sx3 = ., Sy3 = ., Sxy2 = ., Syx2 = .;
for ( const auto &point : vecPoints ) {
Sx += point.x;
Sy += point.y;
Sx2 += point.x * point.x;
Sy2 += point.y * point.y;
Sxy += point.x * point.y;
Sx3 += point.x * point.x * point.x;
Sy3 += point.y * point.y * point.y;
Sxy2 += point.x * point.y * point.y;
Syx2 += point.y * point.x * point.x;
} double A, B, C, D, E;
int n = vecPoints.size();
A = n * Sx2 - Sx * Sx;
B = n * Sxy - Sx * Sy;
C = n * Sy2 - Sy * Sy;
D = 0.5 * ( n * Sxy2 - Sx * Sy2 + n * Sx3 - Sx * Sx2 );
E = 0.5 * ( n * Syx2 - Sy * Sx2 + n * Sy3 - Sy * Sy2 ); auto AC_B2 = ( A * C - B * B); // The variable name is from AC - B^2
auto am = ( D * C - B * E ) / AC_B2;
auto bm = ( A * E - B * D ) / AC_B2; double rSqureSum = .f;
for ( const auto &point : vecPoints )
{
rSqureSum += sqrt ( ( point.x - am ) * ( point.x - am ) + ( point.y - bm) * ( point.y - bm) );
}
float r = static_cast<float>( rSqureSum / n );
rotatedRect.center.x = static_cast<float>( am );
rotatedRect.center.y = static_cast<float>( bm );
rotatedRect.size = cv::Size2f( .f * r, .f * r ); return rotatedRect;
} std::vector<size_t> findPointOverTol( const std::vector<cv::Point2f> &vecPoints, const cv::RotatedRect &rotatedRect, int method, float tolerance )
{
std::vector<size_t> vecResult;
for ( size_t i = ;i < vecPoints.size(); ++ i ) {
cv::Point2f point = vecPoints[i];
auto disToCtr = sqrt( ( point.x - rotatedRect.center.x) * (point.x - rotatedRect.center.x) + ( point.y - rotatedRect.center.y) * ( point.y - rotatedRect.center.y ) );
auto err = disToCtr - rotatedRect.size.width / ;
if ( method == && fabs ( err ) > tolerance ) {
vecResult.push_back(i);
}else if ( method == && err > tolerance ) {
vecResult.push_back(i);
}else if ( method == && err < -tolerance ) {
vecResult.push_back(i);
}
}
return vecResult;
} //method 1 : Exclude all the points out of positive error tolerance and inside the negative error tolerance.
//method 2 : Exclude all the points out of positive error tolerance.
//method 3 : Exclude all the points inside the negative error tolerance.
cv::RotatedRect FitCircleIterate(const std::vector<cv::Point2f> &vecPoints, int method, float tolerance)
{
cv::RotatedRect rotatedRect;
if (vecPoints.size() < )
return rotatedRect; std::vector<cv::Point2f> vecLocalPoints;
for ( const auto &point : vecPoints ) {
vecLocalPoints.push_back ( point );
}
rotatedRect = FitCircle ( vecLocalPoints ); std::vector<size_t> overTolPoints = findPointOverTol ( vecLocalPoints, rotatedRect, method, tolerance );
int nIteratorNum = ;
while ( ! overTolPoints.empty() && nIteratorNum < ) {
for (auto it = overTolPoints.rbegin(); it != overTolPoints.rend(); ++ it)
vecLocalPoints.erase(vecLocalPoints.begin() + *it);
rotatedRect = FitCircle ( vecLocalPoints );
overTolPoints = findPointOverTol ( vecLocalPoints, rotatedRect, method, tolerance );
++ nIteratorNum;
}
return rotatedRect;
} std::vector<cv::Point2f> randomSelectPoints(const std::vector<cv::Point2f> &vecPoints, int needToSelect)
{
std::set<int> setResult;
std::vector<cv::Point2f> vecResultPoints; if ( (int)vecPoints.size() < needToSelect )
return vecResultPoints; while ((int)setResult.size() < needToSelect) {
int nValue = std::rand() % vecPoints.size();
setResult.insert(nValue);
}
for ( auto index : setResult )
vecResultPoints.push_back ( vecPoints[index] );
return vecResultPoints;
} std::vector<cv::Point2f> findPointsInTol( const std::vector<cv::Point2f> &vecPoints, const cv::RotatedRect &rotatedRect, float tolerance )
{
std::vector<cv::Point2f> vecResult;
for ( const auto &point : vecPoints ) {
auto disToCtr = sqrt( ( point.x - rotatedRect.center.x) * (point.x - rotatedRect.center.x) + ( point.y - rotatedRect.center.y) * ( point.y - rotatedRect.center.y ) );
auto err = disToCtr - rotatedRect.size.width / ;
if ( fabs ( err ) < tolerance ) {
vecResult.push_back(point);
}
}
return vecResult;
} /* The ransac algorithm is from paper "Random Sample Consensus: A Paradigm for Model Fitting with Apphcatlons to Image Analysis and Automated Cartography".
* Given a model that requires a minimum of n data points to instantiate
* its free parameters, and a set of data points P such that the number of
* points in P is greater than n, randomly select a subset S1 of
* n data points from P and instantiate the model. Use the instantiated
* model M1 to determine the subset S1* of points in P that are within
* some error tolerance of M1. The set S1* is called the consensus set of
* S1.
* If g (S1*) is greater than some threshold t, which is a function of the
* estimate of the number of gross errors in P, use S1* to compute
* (possibly using least squares) a new model M1* and return.
* If g (S1*) is less than t, randomly select a new subset S2 and repeat the
* above process. If, after some predetermined number of trials, no
* consensus set with t or more members has been found, either solve the
* model with the largest consensus set found, or terminate in failure. */
cv::RotatedRect FitCircleRansac(const std::vector<cv::Point2f> &vecPoints, float tolerance, int maxRansacTime, int nFinishThreshold)
{
cv::RotatedRect fitResult;
if (vecPoints.size() < )
return fitResult; int nRansacTime = ;
const int RANSAC_CIRCLE_POINT = ;
size_t nMaxConsentNum = ; while ( nRansacTime < maxRansacTime ) {
std::vector<cv::Point2f> vecSelectedPoints = randomSelectPoints ( vecPoints, RANSAC_CIRCLE_POINT );
cv::RotatedRect rectReult = FitCircle ( vecSelectedPoints );
vecSelectedPoints = findPointsInTol ( vecPoints, rectReult, tolerance ); if ( vecSelectedPoints.size() >= (size_t)nFinishThreshold ) {
return FitCircle ( vecSelectedPoints );
}
else if ( vecSelectedPoints.size() > nMaxConsentNum )
{
fitResult = FitCircle ( vecSelectedPoints );
nMaxConsentNum = vecSelectedPoints.size();
}
++ nRansacTime;
} return fitResult;
} void TestFitCircle()
{
std::vector<cv::Point2f> vecPoints;
vecPoints.push_back(cv::Point2f(, ));
vecPoints.push_back(cv::Point2f(2.9f, 2.9f));
vecPoints.push_back(cv::Point2f(17.07f, 17.07f));
vecPoints.push_back(cv::Point2f(.f, .f));
vecPoints.push_back(cv::Point2f(, ));
vecPoints.push_back(cv::Point2f(, ));
vecPoints.push_back(cv::Point2f(, ));
vecPoints.push_back(cv::Point2f(, ));
vecPoints.push_back(cv::Point2f(, ));
vecPoints.push_back(cv::Point2f(, )); cv::RotatedRect rectResult;
rectResult = FitCircle(vecPoints); cout << " X, Y " << rectResult.center.x << ", " << rectResult.center.y << " r " << rectResult.size.width / . << endl; rectResult = FitCircleIterate ( vecPoints, , );
cout << "Iterator Result X, Y " << rectResult.center.x << ", " << rectResult.center.y << " r " << rectResult.size.width / . << endl; rectResult = FitCircleRansac ( vecPoints, , , );
cout << "Ransac Result X, Y " << rectResult.center.x << ", " << rectResult.center.y << " r " << rectResult.size.width / . << endl;
}

Modified Least Square Method and Ransan Method to Fit Circle from Data的更多相关文章

  1. 【Go入门教程5】面向对象(method、指针作为receiver、method继承、method重写)

    前面两章我们介绍了函数和struct,那你是否想过函数当作struct的字段一样来处理呢?今天我们就讲解一下函数的另一种形态,带有接收者(receiver)的函数,我们称为method method ...

  2. 关于.ToList(): LINQ to Entities does not recognize the method ‘xxx’ method, and this method cannot be translated into a store expression.

    LINQ to Entities works by translating LINQ queries to SQL queries, then executing the resulting quer ...

  3. java代码中init method和destroy method的三种使用方式

    在java的实际开发过程中,我们可能常常需要使用到init method和destroy method,比如初始化一个对象(bean)后立即初始化(加载)一些数据,在销毁一个对象之前进行垃圾回收等等. ...

  4. Invalid character found in method name. HTTP method names must be tokens

      o.apache.coyote.http11.Http11Processor : Error parsing HTTP request header Note: further occurrenc ...

  5. SpringBoot:Invalid character found in method name. HTTP method names must be tokens

    问题背景 关于SpringBoot应用挂了很久之后,会发生Invalid character found in method name. HTTP method names must be token ...

  6. Day04 -玩弄Ruby的方法:instance method与class method

    前情提要在第三天时,我们解说了如何在class里用include与extend,去使用module的method. Include is for adding methods to an instan ...

  7. tomcat 启动报错 Invalid character found in method name. HTTP method names must be tokens

    解决:Invalid character found in method name. HTTP method names must be tokens   阿里云上弄了一个tomcat,经常半夜发送崩 ...

  8. [Python] Python 之 function, unbound method 和 bound method

    首先看一下以下示例.(Python 2.7) #!/usr/bin/env python # -*- coding: utf-8 -*- class C(object): def foo(self): ...

  9. 【Go入门教程7】面向对象(method、指针作为receiver、method继承、method重写)

    前面两章我们介绍了函数和struct,那你是否想过函数当作struct的字段一样来处理呢?今天我们就讲解一下函数的另一种形态,带有接收者(receiver)的函数,我们称为method method ...

随机推荐

  1. C#固定时间执行指定事件(观察者模式+异步委托)

    最近有个项目需要每天固定的时间去执行指定的事件,发现网上关于这样的文章比较少,而且比较散.通过学习了几篇文章后终于实现了这个功能,在此也特别感谢这些文章的作者们,这也是我第一次在园子里面发文章,望多指 ...

  2. Oracle RAC asm常用命令

    在Oracle RAC环境下,使用grid帐号执行 运行asmcmd进入asm命令模式,如: [grid@oradb-node1 ~]$ asmcmd ASMCMD> ASMCMD> du ...

  3. docker网络配置方法总结

    docker启动时,会在宿主主机上创建一个名为docker0的虚拟网络接口,默认选择172.17.42.1/16,一个16位的子网掩码给容器提供了65534个IP地址.docker0只是一个在绑定到这 ...

  4. 事件驱动之Twsited异步网络框架

    在这之前先了解下什么是事件驱动编程 传统的编程是如下线性模式的: 开始--->代码块A--->代码块B--->代码块C--->代码块D--->......--->结 ...

  5. laravel/lumen 单元测试

    Testing Introduction Application Testing Interacting With Your Application Testing JSON APIs Session ...

  6. Lua学习---Lua的控制结构

    前言 由于之前有c/c++.javascript基础,所以学Lua的时候喜欢拿来和前面的语言比较,这里主要和C比较 1.if...else Lua的if语句格式: if 条件 then 条件成立,运行 ...

  7. Codeforces Round #381 (Div. 2)A. Alyona and copybooks(dfs)

    A. Alyona and copybooks Problem Description: Little girl Alyona is in a shop to buy some copybooks f ...

  8. JDBC 数据库连接池 小结

    原文:http://www.cnblogs.com/lihuiyy/archive/2012/02/14/2351768.html 当对数据库的访问不是很频繁时,可以在每次访问数据库时建立一个连接,用 ...

  9. Spring3.1新特性(转)

    一.Spring2.5之前,我们都是通过实现Controller接口或其他实现来定义我们的处理器类. 二.Spring2.5引入注解式处理器支持,通过@Controller 和 @RequestMap ...

  10. [SQL]复制数据库某一个表到另一个数据库中

    SQL:复制数据库某一个表到另一个数据库中 SELECT * INTO 表1 FROM 表2 --复制表2如果只复制结构而不复制内容或只复制某一列只要加WHERE条件就好了 例子:SELECT * I ...