【问题标题】:How to fit a 2D ellipse to given points and a given focus如何将 2D 椭圆拟合到给定点和给定焦点
【发布时间】:2021-04-20 17:25:59
【问题描述】:

这个问题类似于问题,如何将 2D 椭圆(在 x-y 平面中)拟合到给定点? (见下面的链接) (How to fit a 2D ellipse to given points)

现在,我们知道如何通过 Casey 提供的代码使用最小二乘法拟合具有给定点的 2D 椭圆。 (下面还提供了代码。)基于此代码,如果我不仅想在(0,0)处拟合给定的点,还想拟合给定的焦点,我该怎么做?或者有什么更好的方法吗?

我在想我们是否可以根据椭圆方程 Ax^2 + Bxy + Cy^2 + Dx + Ey=1 推导出焦点(作为 x 和 y 的函数),其中 A、B、C , D, E 是系数,并将其用作最小二乘法的约束。但可悲的是,我也不知道如何获得焦点。

代码

import numpy as np
import matplotlib.pyplot as plt
alpha = 5
beta = 3
N = 500
DIM = 2

np.random.seed(2)

# Generate random points on the unit circle by sampling uniform angles
theta = np.random.uniform(0, 2*np.pi, (N,1))
eps_noise = 0.2 * np.random.normal(size=[N,1])
circle = np.hstack([np.cos(theta), np.sin(theta)])

# Stretch and rotate circle to an ellipse with random linear tranformation
B = np.random.randint(-3, 3, (DIM, DIM))
noisy_ellipse = circle.dot(B) + eps_noise

# Extract x coords and y coords of the ellipse as column vectors
X = noisy_ellipse[:,0:1]
Y = noisy_ellipse[:,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)[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[0], x[1],x[2],x[3],x[4]))

# Plot the noisy data
plt.scatter(X, Y, label='Data Points')

# Plot the original ellipse from which the data was generated
phi = np.linspace(0, 2*np.pi, 1000).reshape((1000,1))
c = np.hstack([np.cos(phi), np.sin(phi)])
ground_truth_ellipse = c.dot(B)
plt.plot(ground_truth_ellipse[:,0], ground_truth_ellipse[:,1], 'k--', label='Generating Ellipse')

# Plot the least squares ellipse
x_coord = np.linspace(-5,5,300)
y_coord = np.linspace(-5,5,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()

【问题讨论】:

  • 如果你从点得到方程,那么找到焦点的坐标有什么问题?
  • 等式中的焦点可能不在 (0,0)。我正在尝试找到一个最适合点的椭圆,并且焦点位于 (0,0)。
  • 根据另一个终点和您需要的任何其他参数写出椭圆的方程。可能只是主轴。这是要解决的三个参数,因为您修复了五个参数中的两个。
  • 非常感谢您的回复。我正在努力。

标签: python least-squares


【解决方案1】:

对于一个焦点在(0,0)的椭圆,椭圆在极坐标下的方程可以写成:

假设 ? = 半长轴,? = 偏心率,另一个焦点在角度 ?,

现在,我们可以使用数据点(??,??)通过非线性最小二乘法(例如:Levenberg–Marquardt 算法)拟合上述方程。

即求以下方程的最小值:

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 2012-11-18
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    相关资源
    最近更新 更多