问题描述
当前尝试使用scipy的插值实现创建均匀的三次B样条曲线(钳位).当使用interpolate.splev()时,我传入的目标(x)值发生了变化,并且该函数向我返回了一个接近但与目标值不相同的点的x值(以及错误的x值的正确y值).有人对我如何解决此问题有任何建议吗?下面提供的代码可以重新创建问题.预先非常感谢:)
Currently trying to use scipy's implementation of interpolate to create a uniform cubic B-spline (clamped). When using interpolate.splev() the target (x) value I pass in is changed and the function returns me the x value of a point near but not the same as the target value (and the correct y value for the wrong x value). Anybody got any advice on how I can resolve this problem? Code provided below to recreate problem. Thank you very much in advance :)
import numpy as np
import random as rd
from scipy import interpolate
import matplotlib.pyplot as plt
# The number of knots to form spline.
knots = 11
# Creating the x and y values for the knots.
x = np.linspace(0, 1, knots, endpoint=True)
y = np.array([rd.random() for i in range(knots)])
# Knot Vector.
t = np.linspace(0, 1, len(x) - 2, endpoint=True)
t = np.append([0, 0, 0], t)
t = np.append(t, [1, 1, 1])
# Cubic Spline definition.
spline = [t, [x, y], 3]
# =====================================================================
# X value I want to predict the y value off.
target = rd.random()
# Using spline evaluate to get the value of the "target".
prediction = interpolate.splev(target, spline)
print("X Value given to .splev:", target)
print("What .splev sees: x =", prediction[0], ", y =", prediction[1])
# =====================================================================
# Plotting the control points.
plt.plot(x, y, 'k--', label='Control Polygon', marker='o', markerfacecolor='red')
# Output used for display purposes only.
out = interpolate.splev(np.linspace(0, 1, 1000, endpoint=True), spline)
# Plotting the b-spline line.
plt.plot(out[0], out[1], 'b', linewidth=2.0, label='B-spline curve')
plt.grid(True)
plt.show()
更新代码:
import matplotlib.pyplot as plt
from scipy.interpolate import splev, splrep
import numpy as np
import random as rd
knots = 11
# X knots equidistant apart and Y random.
x = np.linspace(0, 1, knots, endpoint=True)
y = np.array([rd.random() for i in range(knots)])
# Creating the spline using slrep.
spline = splrep(x, y, s=0)
x2 = np.linspace(0, 1, 200)
y2 = splev(x2, spline)
# Plotting the a random point with target (x) and the predicted (y).
target = rd.random()
prediction = splev(target, spline)
plt.plot(target, prediction, 'o')
# Plotting the spline.
plt.plot(x, y, 'o', x2, y2)
plt.grid(True)
plt.show()
推荐答案
splev接受一个由结和系数组成的元组.要拟合数据,请使用 tck = splrep(x,y,s = 0);splev(xnew,tck)
或 make_interp_spline
.
splev accepts a tuple of knots and coefficients. To fit the data, use tck= splrep(x, y, s=0); splev(xnew, tck)
, or make_interp_spline
.
要创建具有给定系数的splne对象,请使用 BSpline(t,c,k)
To create a splne object with given coefficients, use BSpline(t, c, k)
这篇关于scipy.interpolate输入值的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!