最小二乘法拟合圆公式推导及vc实现[r]
最小二乘法(least squares analysis)是一种 数学 优化 技术,它通过 最小化 误差 的平方和找到一组数据的最佳 函数 匹配。 最小二乘法是用最简的方法求得一些绝对不可知的真值,而令误差平方之和为最小。 最小二乘法通常用于 曲线拟合 (least squares fitting) 。这里有 拟合圆曲线 的公式推导过程 和 vc实现。
VC实现的代码:
工程下载
编译运行后随便打开一个图片,当然最好是全白的图片,然后就点吧,大于三个点后就会开始拟合。红线画的圆为拟合的圆,深蓝的点为鼠标点击设置的样本点。单击鼠标右键清空样本集。
VC实现的代码:
void CViewActionImageTool::LeastSquaresFitting()
{
if (m_nNum<3)
{
return;
}
int i=0;
double X1=0;
double Y1=0;
double X2=0;
double Y2=0;
double X3=0;
double Y3=0;
double X1Y1=0;
double X1Y2=0;
double X2Y1=0;
for (i=0;i<m_nNum;i++)
{
X1 = X1 + m_points[i].x;
Y1 = Y1 + m_points[i].y;
X2 = X2 + m_points[i].x*m_points[i].x;
Y2 = Y2 + m_points[i].y*m_points[i].y;
X3 = X3 + m_points[i].x*m_points[i].x*m_points[i].x;
Y3 = Y3 + m_points[i].y*m_points[i].y*m_points[i].y;
X1Y1 = X1Y1 + m_points[i].x*m_points[i].y;
X1Y2 = X1Y2 + m_points[i].x*m_points[i].y*m_points[i].y;
X2Y1 = X2Y1 + m_points[i].x*m_points[i].x*m_points[i].y;
}
double C,D,E,G,H,N;
double a,b,c;
N = m_nNum;
C = N*X2 - X1*X1;
D = N*X1Y1 - X1*Y1;
E = N*X3 + N*X1Y2 - (X2+Y2)*X1;
G = N*Y2 - Y1*Y1;
H = N*X2Y1 + N*Y3 - (X2+Y2)*Y1;
a = (H*D-E*G)/(C*G-D*D);
b = (H*C-E*D)/(D*D-G*C);
c = -(a*X1 + b*Y1 + X2 + Y2)/N;
double A,B,R;
A = a/(-2);
B = b/(-2);
R = sqrt(a*a+b*b-4*c)/2;
m_fCenterX = A;
m_fCenterY = B;
m_fRadius = R;
return;
}
{
if (m_nNum<3)
{
return;
}
int i=0;
double X1=0;
double Y1=0;
double X2=0;
double Y2=0;
double X3=0;
double Y3=0;
double X1Y1=0;
double X1Y2=0;
double X2Y1=0;
for (i=0;i<m_nNum;i++)
{
X1 = X1 + m_points[i].x;
Y1 = Y1 + m_points[i].y;
X2 = X2 + m_points[i].x*m_points[i].x;
Y2 = Y2 + m_points[i].y*m_points[i].y;
X3 = X3 + m_points[i].x*m_points[i].x*m_points[i].x;
Y3 = Y3 + m_points[i].y*m_points[i].y*m_points[i].y;
X1Y1 = X1Y1 + m_points[i].x*m_points[i].y;
X1Y2 = X1Y2 + m_points[i].x*m_points[i].y*m_points[i].y;
X2Y1 = X2Y1 + m_points[i].x*m_points[i].x*m_points[i].y;
}
double C,D,E,G,H,N;
double a,b,c;
N = m_nNum;
C = N*X2 - X1*X1;
D = N*X1Y1 - X1*Y1;
E = N*X3 + N*X1Y2 - (X2+Y2)*X1;
G = N*Y2 - Y1*Y1;
H = N*X2Y1 + N*Y3 - (X2+Y2)*Y1;
a = (H*D-E*G)/(C*G-D*D);
b = (H*C-E*D)/(D*D-G*C);
c = -(a*X1 + b*Y1 + X2 + Y2)/N;
double A,B,R;
A = a/(-2);
B = b/(-2);
R = sqrt(a*a+b*b-4*c)/2;
m_fCenterX = A;
m_fCenterY = B;
m_fRadius = R;
return;
}
工程下载
编译运行后随便打开一个图片,当然最好是全白的图片,然后就点吧,大于三个点后就会开始拟合。红线画的圆为拟合的圆,深蓝的点为鼠标点击设置的样本点。单击鼠标右键清空样本集。
路漫漫其修远兮 吾将上下而求索
my blog