scipy:插值轨迹

时间:2013-01-09 18:46:35

标签: python interpolation spline

我有一系列(x,y)对形成的轨迹。我想用样条曲线在这条轨迹上插入点。

我该怎么做?使用scipy.interpolate.UnivariateSpline不起作用,因为 x y 都不是单调的。我可以引入参数化(例如沿着轨迹的长度 d ),但是我有两个因变量 x(d) y(d)

示例:

import numpy as np
import matplotlib.pyplot as plt
import math

error = 0.1
x0 = 1
y0 = 1
r0 = 0.5

alpha = np.linspace(0, 2*math.pi, 40, endpoint=False)
r = r0 + error * np.random.random(len(alpha))
x = x0 + r * np.cos(alpha)
y = x0 + r * np.sin(alpha)
plt.scatter(x, y, color='blue', label='given')

# For this special case, the following code produces the
# desired results. However, I need something that depends
# only on x and y:
from scipy.interpolate import interp1d
alpha_i = np.linspace(alpha[0], alpha[-1], 100)
r_i = interp1d(alpha, r, kind=3)(alpha_i)
x_i = x0 + r_i * np.cos(alpha_i)
y_i = x0 + r_i * np.sin(alpha_i)
plt.plot(x_i, y_i, color='green', label='desired')

plt.legend()
plt.show()

example data

1 个答案:

答案 0 :(得分:14)

使用splprep可以在任何几何体的曲线上进行插值。

from scipy import interpolate
tck,u=interpolate.splprep([x,y],s=0.0)
x_i,y_i= interpolate.splev(np.linspace(0,1,100),tck)

这会产生类似给定的图,但仅使用x和y点,而不是alpha和r参数。 Same as yours only using x and y points.

抱歉我的原始答案,我误解了这个问题。