找到包含两/三个平面坐标点的椭圆点集

本文介绍了如何使用numpy库中的fit_ellipse函数,通过给定两点或三点数据,计算并绘制椭圆散点图。函数根据给定的扩展比和离心率,生成椭圆上的点集,适用于数据可视化中的椭圆拟合应用。
摘要由CSDN通过智能技术生成

直接上代码

import numpy as np
def fit_ellipse(points:np.array = None, extension_ratio: float = 0.2, eccentricity: float = 0.8, n_points: int = 100):
    center = np.mean(points, axis=0)
    if points.shape[0] == 2:
        axis_vector = points[1] - points[0]
        distance = np.linalg.norm(axis_vector)
        c = distance / 2 * (1 +extension_ratio)
    elif points.shape[0] == 3:
        radius = np.linalg.norm(points - center, axis=1)
        max_radius_index = np.argmax(radius)
        axis_vector = points[max_radius_index] - center
        c = np.max(radius) * (1 + extension_ratio)
    a = c / eccentricity
    b = np.sqrt(a**2-c**2)
    rotation_angle = np.arctan2(axis_vector[1], axis_vector[0])
    theta = np.linspace(0, 2*np.pi, n_points)
    dx = a * np.cos(theta)
    dy = b * np.sin(theta)
    x_rotated = dx * np.cos(rotation_angle) - dy * np.sin(rotation_angle) + center[0]
    y_rotated = dx * np.sin(rotation_angle) + dy * np.cos(rotation_angle) + center[1]
    return np.column_stack((x_rotated, y_rotated))

两个点的情况

points = np.array([[1,3],[5,6]])
ellipse_points = fit_ellipse(points, extension_ratio = 0.8, eccentricity=0.9)
plt.scatter(ellipse_points[:, 0], ellipse_points[:, 1])
plt.scatter(points[:, 0], points[:, 1], color='red')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Ellipse Scatter Plot')
plt.gca().set_aspect('equal', adjustable='box')
plt.grid(True)
plt.show()

三个点的情况

points = np.array([[-5,3],[5,6],[3,9]])
ellipse_points = fit_ellipse(points, extension_ratio = 0.8, eccentricity=0.9)
plt.scatter(ellipse_points[:, 0], ellipse_points[:, 1])
plt.scatter(points[:, 0], points[:, 1], color='red')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Ellipse Scatter Plot')
plt.gca().set_aspect('equal', adjustable='box')
plt.grid(True)
plt.show()

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值