【问题标题】:Parametric Curve Fitting Using Python使用 Python 进行参数曲线拟合
【发布时间】:2021-10-01 18:40:59
【问题描述】:

我想将参数曲线与一组点进行最佳拟合。曲线的起点和终点应分别与第一个和最后一个采样点重合。

我在下面尝试过这段代码,但它给了我一个闭合曲线。有没有办法稍微修改这段代码以确保曲线不闭合?

import numpy as np
from scipy import interpolate
from matplotlib import pyplot as plt

x = np.array([23, 24, 24, 25, 25])
y = np.array([13, 12, 13, 12, 13])

# append the starting x,y coordinates
x = np.r_[x, x[0]]
y = np.r_[y, y[0]]

# fit splines to x=f(u) and y=g(u), treating both as periodic. also note that s=0
# is needed in order to force the spline fit to pass through all the input points.
tck, u = interpolate.splprep([x, y], s=0, per=True)

# evaluate the spline fits for 1000 evenly spaced distance values
xi, yi = interpolate.splev(np.linspace(0, 1, 1000), tck)

# plot the result
fig, ax = plt.subplots(1, 1)
ax.plot(x, y, 'or')
ax.plot(xi, yi, '-b')'''

非常感谢您的帮助。

【问题讨论】:

    标签: python scipy curve-fitting bezier spline


    【解决方案1】:

    您将第一个 x 和 y 值附加到 x 和 y 数组的末尾:

    # append the starting x,y coordinates
    x = np.r_[x, x[0]]
    y = np.r_[y, y[0]]
    

    ..这意味着您希望样条曲线在它开始的同一位置结束,然后您告诉interpolate.splprep 函数您需要带有per=True 关键字参数的周期性曲线:

    tck, u = interpolate.splprep([x, y], per=True, s=0)
    

    ..这会给你你得到的东西..:

    只需删除将最后一个 x 和 y 值附加到 x 和 y 数组的两行,并删除 per=True 关键字参数,您就会得到所需的内容:

    import numpy as np
    from scipy import interpolate
    from matplotlib import pyplot as plt
    
    x = np.array([23, 24, 24, 25, 25])
    y = np.array([13, 12, 13, 12, 13])
    
    # append the starting x,y coordinates
    # x = np.r_[x, x[0]]
    # y = np.r_[y, y[0]]
    
    # fit splines to x=f(u) and y=g(u), treating both as periodic. also note that s=0
    # is needed in order to force the spline fit to pass through all the input points.
    # tck, u = interpolate.splprep([x, y], per=True, s=0)
    tck, u = interpolate.splprep([x, y], s=0)
    
    # evaluate the spline fits for 1000 evenly spaced distance values
    xi, yi = interpolate.splev(np.linspace(0, 1, 1000), tck)
    
    # plot the result
    fig, ax = plt.subplots(1, 1)
    ax.plot(x, y, 'or')
    ax.plot(xi, yi, '-b')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 2018-05-24
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 2020-03-19
      • 1970-01-01
      相关资源
      最近更新 更多