使用一组坐标信息拟合圆(matlab)
程序员文章站
2022-03-31 20:53:48
...
详细原理参考MATLAB圆拟合
圆拟合
function [xc,yc,R,a] = circfit(x,y)
%圆拟合函数
%CIRCFIT Fits a circle in x,y plane
% [XC, YC, R, A] = CIRCFIT(X,Y)
% Result is center point (yc,xc) and radius R.A is an
% optional output describing the circle’s equation:
%
% x^2+y^2+a(1)*x+a(2)*y+a(3)=0
% by Bucher izhak 25/oct/1991
n=length(x); xx=x.*x; yy=y.*y; xy=x.*y;
A=[sum(x) sum(y) n;sum(xy) sum(yy)...
sum(y);sum(xx) sum(xy) sum(x)];
B=[-sum(xx+yy) ; -sum(xx.*y+yy.*y) ; -sum(xx.*x+xy.*y)];
a=A\B; %x = A\B 用来求解线性方程 A*x = B. A 和 B 的行数一致.
xc = -.5*a(1);
yc = -.5*a(2);
R = sqrt((a(1)^2+a(2)^2)/4-a(3));
end
处理数据,输出图片
%输入数据
m=xlsread('input/xiwo8.xls');
x=m(:,1);
y=m(:,2);
%拟合圆
[xc,yc,R,a] = circfit(x,y);
%画图,并存图
theta=5/4*pi:0.1:7/4*pi;
Circle1=xc+R*cos(theta);
Circle2=yc+R*sin(theta);
plot(Circle1,Circle2,'g','linewidth',1);
hold on;
%plot(x,y,'r','linewidth',1);
scatter(x,y,2,'r');
axis equal
title(['xc=',num2str(xc),', yc=',num2str(yc),', R=',num2str(R)]);
data=[xc,yc,R]
%保存数据
% data=['xc','yc','R'];
% [M,N]=size(data);
% data_cell=num2cell(data,ones(M,1),ones(N,1));
处理结果值
m=xlsread('output/result.xls');
y1=m(:,1);
y2=m(:,2);
y3=m(:,3);
x=[1:1:8];
%xc
plot(x,y1,'r','linewidth',1);
title('xc');
waitforbuttonpress;
%yc
plot(x,y2,'g','linewidth',1);
title('yc');
waitforbuttonpress;
%R
plot(x,y3,'b','linewidth',1);
title('R');
waitforbuttonpress;
plot(x,y1,'r','linewidth',1);
% legend('xc');
hold on;
plot(x,y2,'g','linewidth',1);
% legend('yc');
hold on;
plot(x,y3,'b','linewidth',1);
legend('xc','yc','R');
推荐阅读