【问题标题】:Interpolating a closed curve using scipy使用 scipy 插值闭合曲线
【发布时间】:2016-03-01 23:17:45
【问题描述】:

我正在编写一个 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) 

这给了我这样的曲线:

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

【问题讨论】:

标签: python numpy scipy interpolation curve-fitting


【解决方案1】:

你的闭合路径可以看成是一条参数曲线,x=f(u), y=g(u) 其中u是沿曲线的距离,以区间 [0, 1) 为界。您可以使用scipy.interpolate.splprepper=Truexy 点视为周期性点,然后使用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')

【讨论】:

  • 如果我不附加起始坐标,它就完美了。
  • 真的吗?对我不起作用 - 如果我不附加起始坐标,我会得到一个“数字 8”。 per 参数的文档还说 “如果非零,则数据点被认为是周期性的,周期为 x[m-1] - x[0],并返回平滑的周期性样条近似值。y[ m-1] 和 w[m-1] 没有被使用。”,这表明它将忽略 xy 中的最后一个坐标。
  • 如果我附加坐标,我会遇到这个问题:mail.scipy.org/pipermail/scipy-user/2007-September/013650.html
  • 很奇怪。也许它与版本有关?我只能说,使用 scipy 0.14.1 和 0.16.0 附加起始坐标对我来说非常有效,而不附加它们会导致八字形曲线不通过 (25, 13) 处的点.也许这与您在 (22, 13) 处的情节中的额外点有关?
  • @ali_m 是否可以评估样条拟合 n 特定值(而不是 1000 个均匀间隔的距离值)?
猜你喜欢
  • 2021-01-05
  • 2017-04-21
  • 2018-07-07
  • 2018-11-20
  • 1970-01-01
  • 2020-05-05
  • 2021-11-01
  • 2020-07-12
  • 2013-10-10
相关资源
最近更新 更多