问题描述
我想将参数曲线最适合一组点。曲线的起点和终点应分别与第一个和最后一个采样点重合。
我已经尝试过下面的代码,但它给了我一个封闭的曲线。有没有办法稍微修改一下这段代码,确保曲线不闭合?
import numpy as np
from scipy import interpolate
from matplotlib import pyplot as plt
x = np.array([23,24,25,25])
y = np.array([13,12,13,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')'''
非常感谢您的帮助。
解决方法
您将第一个 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,25,25])
y = np.array([13,12,13,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,s=0)
tck,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()