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. [开源项目]Hibernate基本使用

    开源项目(1)Hibernate基本使用 Hibernate介绍 Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象 ...

  2. Oracle 使用SqlPlus管理

    Oracle 使用SqlPlus 安装,一键安装,很简单.安装过程,一定要记住密码 一.登陆sqlplus 连接本地服务器,可以直接,打开cmd: 可以直接不用登陆,如果登陆需要输入用户名.密码. s ...

  3. vmware安装无法打开内核设备 \\.\Global\vmx86: 系统找不到指定的文件

    刚刚安装好了虚拟机,Windows XP 64bit Professional,安装好了开发环境,然后重启机器后虚拟机就打不开了,提示“vmware安装无法打开内核设备 \\.\Global\vmx8 ...

  4. [LeetCode] 8. String to Integer (atoi)

    Implement atoi to convert a string to an integer. public class Solution { public int myAtoi(String s ...

  5. http load 的使用以及参数解释

    http load 的使用以及参数解释   1.参数含义 参数     全称      含义 -p        -parallel     并发的用户进程数.-f        -fetches   ...

  6. MySQL服务 - MySQL变量类型及变量设置

    一.MySQL变量类型: MySQL通过变量来定义当前服务器的特性,保存状态信息等.我们可以通过手动更改变量的值来配置MySQL,也可以通过变量获得MySQL的当前状态信息.MySQL的变量类型可以从 ...

  7. 一. DotNet MVC4.0+EasyUI Web简单框架-前言

    之所以说它简单,是因为仅仅用了大家最熟悉的三层架构,简单明了 1.先新建一个MVC4.0 Web项目 2.添加EasyUI的引用,放到Script底下 http://files.cnblogs.com ...

  8. SparkConf加载与SparkContext创建(源码阅读二)

    紧接着昨天,我们继续开搞了啊.. 1.下面,开始创建BroadcastManager,就是传说中的广播变量管理器.BroadcastManager用于将配置信息和序列化后的RDD.Job以及Shuff ...

  9. es let2

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  10. js多文件上传

    一.HTML 选择文件的时候可以选择多个文件,这个需要我们在input file 里面加入一个属性multiple="multiple" 这样就可以框选文件了 <!DOCTY ...