def fit_circle(df):
x = df['inner'] y = df['height'] df_list, name_list = load_data('凸轮轴信号轮,球形测头_10次5101(1)')
x_m = mean(x) y_m = mean(y)
method_2 = "leastsq"
def calc_R(c): """ calculate the distance of each 2D points from the center c=(xc, yc) """ return sqrt((x - c[0]) ** 2 + (y - c[1]) ** 2)
def calc_ecart(c): """ calculate the algebraic distance between the 2D points and the mean circle centered at c=(xc, yc) """ Ri = calc_R(c) return Ri - Ri.mean()
center_estimate = x_m, y_m center_2, ier = optimize.leastsq(calc_ecart, center_estimate)
xc_2, yc_2 = center_2 Ri_2 = calc_R(center_2) R_2 = Ri_2.mean() residu_2 = sum((Ri_2 - R_2) ** 2)
print('x={},y={},r={}'.format(xc_2,yc_2,R_2))
from matplotlib import pyplot as p, cm
f = p.figure() p.plot(x, y, 'ro', label='data', ms=9, mec='b', mew=1)
theta_fit = linspace(-pi, pi, 180)
x_fit2 = xc_2 + R_2 * cos(theta_fit) y_fit2 = yc_2 + R_2 * sin(theta_fit) p.plot(x_fit2, y_fit2, 'k--', label=method_2, lw=2)
p.plot([xc_2], [yc_2], 'gD', mec='r', mew=1)
p.grid() p.title('Leasts Squares Circle') p.show()
|