How to find the center of circle using the least square fit in python?

Your data points seem fairly clean and I see no outliers, so many circle fitting algorithms will work.

I recommend you to start with the Coope method, which works by magically linearizing the problem:

(X-Xc)² + (Y-Yc)² = R² is rewritten as

2 Xc X + 2 Yc Y + R² - Xc² - Yc² = X² + Y², then

A X + B Y + C = X² + Y², solved by linear least squares.


I do not have any experience fitting circles, but I have worked with the more general case of fitting ellipses. Doing this in a correct way with noisy data is not trivial. For this problem, the algorithm described in Numerically stable direct least squares fitting of ellipses by Halir and Flusser works pretty well. The paper includes Matlab code, which should be straightforward to translate to Numpy. Maybe you could use this algorithm to fit an ellipse and then take the average of the two axis as the radius or so. Some of the references in the paper also mention fitting circles, you might want to look those up.


As a follow up to Bas Swinckels post, I figured I'd post my code implementing the Halir and Flusser method of fitting an ellipse

https://github.com/bdhammel/least-squares-ellipse-fitting

Using the above code you can find the center with the following method.

from ellipses import LSqEllipse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

lsqe = LSqEllipse()
lsqe.fit(data)
center, width, height, phi = lsqe.parameters()

plt.close('all')
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)
ax.axis('equal')
ax.plot(data[0], data[1], 'ro', label='test data', zorder=1)

ellipse = Ellipse(xy=center, width=2*width, height=2*height, angle=np.rad2deg(phi),
               edgecolor='b', fc='None', lw=2, label='Fit', zorder = 2)
ax.add_patch(ellipse)

plt.legend()
plt.show()

enter image description here