改编自How to fit a 2D ellipse to given points.
这应该是一个好的开始。
import numpy as np
import matplotlib.pyplot as plt
# circle = np.array([(0,1),(1,0),(0,-1),(-1,0)])
circle = np.array([(0,1),(1.2,0),(0,-0.9),(-1,0)])
# Extract x coords and y coords of the ellipse as column vectors
X = circle[:,0:1]
Y = circle[:,1:]
# Formulate and solve the least squares problem ||Ax - b ||^2
A = np.hstack([X**2, X * Y, Y**2, X, Y])
b = np.ones_like(X)
x = np.linalg.lstsq(A, b, rcond=-1)[0].squeeze()
# Print the equation of the ellipse in standard form
print('The ellipse is given by {0:.3}x^2 + {1:.3}xy +{2:.3}y^2 +{3:.3}x + {4:.3}y = 1'.format(*x))
# Plot the circle
plt.scatter(X, Y, label='Data Points')
# Plot the least squares ellipse
x_coord = np.linspace(-2,2,300)
y_coord = np.linspace(-2,2,300)
X_coord, Y_coord = np.meshgrid(x_coord, y_coord)
Z_coord = x[0] * X_coord ** 2 + x[1] * X_coord * Y_coord + x[2] * Y_coord**2 + x[3] * X_coord + x[4] * Y_coord
plt.contour(X_coord, Y_coord, Z_coord, levels=[1], colors=('r'), linewidths=2)
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.show()