2015-11-27 66 views
3

我正在写一个python脚本来插入一些给定的样条点。点由它们的[x, y]坐标定义。使用scipy插值闭合曲线

我试图用这个代码:

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) 

,给了我这样一个曲线:

不过,我需要有一个平滑的闭合曲线 - 在上面的图片其中一个点的衍生物显然不相同。 我该如何做到这一点?

+1

相当http://stackoverflow.com/questions/33739006的副本/ how-to-smooth-this-data/33746521#33746521 – lejlot

+1

@lejlot你说的对,但是这个问题是一个更好的问题 –

+0

问题是一样的,答案是一样的,什么是“酷”并不重要“;) – lejlot

回答

4

你的闭合路径可以被认为是一个参数曲线,X = F(U)Y =克(U)其中Ú是沿曲线的距离,有界上的间隔[0, 1)。您可以使用scipy.interpolate.splprepper=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

+0

如果我不追加起始坐标,它会很完美。 – sooobus

+0

真的吗?不适合我 - 如果我不追加起始坐标,我会得到'8的数字'。 “per”参数的文档还会说*“如果非零,则数据点被认为是周期性的,周期为x [m-1] - x [0],并返回一个平滑的周期样条近似值y [m- 1]和w [m-1]不使用。“*,这表明它会忽略'x'和'y'中的最后一个坐标。 –

+0

我得到这个问题,如果我追加坐标:https://mail.scipy.org/pipermail/scipy-user/2007-September/013650.html – sooobus