python-已知三点求圆心和半径

# 已知三点坐标,求外接圆圆心坐标与半径。

x=((y2-y1)*(y3*y3-y1*y1+x3*x3-x1*x1)-(y3-y1)*(y2*y2-y1*y1+x2*x2-x1*x1))/(2.0*((x3-x1)*(y2-y1)-(x2-x1)*(y3-y1)))
y=((x2-x1)*(x3*x3-x1*x1+y3*y3-y1*y1)-(x3-x1)*(x2*x2-x1*x1+y2*y2-y1*y1))/(2.0*((y3-y1)*(x2-x1)-(y2-y1)*(x3-x1)))
r=(x1-x)*(x1-x+(y1-y)*(y1-y)

最小二乘法拟合圆

Least_Squares_Circle

def fit_circle(df):
# Coordinates of the 2D points
# x = r_[ 20.9564, 20.9593,20.9629]
# y = r_[ 30.1163, 30.0848,30.0259]

# x = r_[9, 35, -13, 10, 23, 0]
# y = r_[34, 10, 6, -14, 27, -10]

x = df['inner']
y = df['height']
df_list, name_list = load_data('凸轮轴信号轮,球形测头_10次5101(1)')

# coordinates of the barycenter
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()