python之拟合圆心及半径
目录
1、公式推导
2、代码实现
1、公式推导
2、代码实现
import matplotlib.pyplot as plt
import numpy as np
def Show_Fig(X,Y,x, y, r):
theta = np.arange(0, 2 * np.pi, 0.01)
x = x + r * np.cos(theta)
y = y + r * np.sin(theta)
fig = plt.figure()
axes = fig.add_subplot(111)
axes.plot(x, y)
axes.plot(X, Y,"r*")
axes.axis('equal')
plt.show()
def Fit_Circle(x=None, y=None):
C = []
A = []
for i in range(len(x)):
A.append([x[i], y[i], 1])
C.append(np.square(x[i]) + np.square(y[i]))
A = np.mat(A)
B = np.dot(np.dot(np.linalg.inv(np.dot(A.T, A)), A.T), C)
B = np.array(B, dtype='float32').flatten()
return B[0]/2, B[1]/2, np.sqrt(B[2]+np.square(B[0])/4 + np.square(B[1])/4)
if __name__ == '__main__':
# 定义圆的参数
center_x = 1
center_y = 2
radius = 5
# 生成圆上的点
theta = np.linspace(0, 2 * np.pi, 100) # 生成一个角度范围
x = center_x + radius * np.cos(theta) # x坐标
y = center_y + radius * np.sin(theta) # y坐标
# 添加噪声
noise = np.random.normal(0, 0.05, size=(100,)) # 生成一个标准正态分布的噪声
X = x + noise
Y = y + noise
fitcenter_x, fitcenter_y, fitradius = Fit_Circle(x=X, y=Y)
print(f"拟合得到的圆心是:({fitcenter_x}, {fitcenter_y}), 半径是:{fitradius}")
Show_Fig(X,Y,fitcenter_x, fitcenter_y, fitradius)
拟合得到的圆心是:(1.0052670240402222, 2.0036354064941406), 半径是:5.004283869935406