python - 使用 scipy 插值闭合曲线

标签 python numpy scipy interpolation curve-fitting

我正在编写一个 python 脚本来使用样条插值一组给定的点。这些点由它们的 [x, y] 坐标定义。

我尝试使用这段代码:

x = np.array([23, 24, 24, 25, 25])
y = np.array([13, 12, 13, 12, 13])
tck, u = scipy.interpolate.splprep([x,y], s=0)
unew = np.arange(0, 1.00, 0.005)
out = scipy.interpolate.splev(unew, tck) 

这给了我这样的曲线:

Bad Interpolation

但是,我需要一条平滑的闭合曲线——在上图中,其中一个点的导数显然不相同。 我怎样才能做到这一点?

最佳答案

您的闭合路径可以被视为参数曲线,x=f(u)y=g(u) 其中u是沿曲线的距离,以区间 [0, 1) 为界。您可以使用 scipy.interpolate.splprep使用 per=True 将您的 xy 点视为周期性点,然后使用 scipy.interpolate.splev 评估拟合样条曲线:

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')

enter image description here

关于python - 使用 scipy 插值闭合曲线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33962717/

相关文章:

python - 如何从设定时间中减去当前时间

python - webdriver 等待多个元素之一出现

python - 如何将 panda DataFrame 中的特定范围的元素转换为 float ?

python - 求函数的最小值?

python - f_oneway 当数据为列表形式时

python - 根据特定单元格中的值移动 pd.dataframe 的行

python - 将动态函数应用于相空间中的每个点(由二维矩阵表示)

python - 切片 numpy 数组

python - 我认为 scipy.interpolate 可能坏了还是我用错了?

python - 如何将 Python 捆绑到 macos .app 应用程序中?