我正在尝试执行以下操作(从维基百科中提取的图像)
#!/usr/bin/env python
from scipy import interpolate
import numpy as np
import matplotlib.pyplot as plt
# sampling
x = np.linspace(0, 10, 10)
y = np.sin(x)
# spline trough all the sampled points
tck = interpolate.splrep(x, y)
x2 = np.linspace(0, 10, 200)
y2 = interpolate.splev(x2, tck)
# spline with all the middle points as knots (not working yet)
# knots = x[1:-1] # it should be something like this
knots = np.array([x[1]]) # not working with above line and just seeing what this line does
weights = np.concatenate(([1],np.ones(x.shape[0]-2)*.01,[1]))
tck = interpolate.splrep(x, y, t=knots, w=weights)
x3 = np.linspace(0, 10, 200)
y3 = interpolate.splev(x2, tck)
# plot
plt.plot(x, y, 'go', x2, y2, 'b', x3, y3,'r')
plt.show()
代码的第一部分是从the main reference中提取的代码,但没有解释如何将这些点用作控制结。
此代码的结果如下图所示。
点是样本,蓝线是考虑所有点的样条。而红线是不适合我的那条线。我试图将所有中间点视为控制结,但我不能。如果我尝试使用knots=x[1:-1]
它就行不通。我很感激任何帮助。
简短问题:如何在样条函数中使用所有中间点作为控制结?
注意:最后一张图片正是我需要的,它是我所拥有的(样条传递所有点)和我需要的(带有控制结的样条)之间的区别。有任何想法吗?
答案 0 :(得分:6)
在这个IPython Notebook http://nbviewer.ipython.org/github/empet/geom_modeling/blob/master/FP-Bezier-Bspline.ipynb中,您可以找到生成B样条曲线所涉及的数据的详细描述,以及de Boor算法的Python实现。
答案 1 :(得分:6)
如果您想要评估bspline,则需要为样条线找出合适的结矢量,然后手动重建tck
以满足您的需求。
tck
代表结t
+系数c
+曲线度k
。 splrep
为通过给定控制点的三次曲线计算tck
。所以你不能把它用于你想要的东西。
以下功能将向您展示我的a similar question I asked some time ago.解决方案,并根据您的需要进行调整。
有趣的事实:代码适用于任何维度的曲线(1D,2D,3D,...,nD)
import numpy as np
import scipy.interpolate as si
def bspline(cv, n=100, degree=3):
""" Calculate n samples on a bspline
cv : Array ov control vertices
n : Number of samples to return
degree: Curve degree
"""
cv = np.asarray(cv)
count = cv.shape[0]
# Prevent degree from exceeding count-1, otherwise splev will crash
degree = np.clip(degree,1,count-1)
# Calculate knot vector
kv = np.array([0]*degree + range(count-degree+1) + [count-degree]*degree,dtype='int')
# Calculate query range
u = np.linspace(0,(count-degree),n)
# Calculate result
return np.array(si.splev(u, (kv,cv.T,degree))).T
测试它:
import matplotlib.pyplot as plt
colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')
cv = np.array([[ 50., 25.],
[ 59., 12.],
[ 50., 10.],
[ 57., 2.],
[ 40., 4.],
[ 40., 14.]])
plt.plot(cv[:,0],cv[:,1], 'o-', label='Control Points')
for d in range(1,5):
p = bspline(cv,n=100,degree=d,periodic=True)
x,y = p.T
plt.plot(x,y,'k-',label='Degree %s'%d,color=colors[d%len(colors)])
plt.minorticks_on()
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(35, 70)
plt.ylim(0, 30)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
结果:
答案 2 :(得分:1)
我认为问题是与你结矢量。如果选择太多结,它似乎会引起问题,它需要在结之间有一些数据点。这个问题解决了问题Bug (?) on selecting knots on scipy.insterpolate's splrep function
#!/usr/bin/env python
from scipy import interpolate
import numpy as np
import matplotlib.pyplot as plt
# sampling
x = np.linspace(0, 10, 10)
y = np.sin(x)
# spline trough all the sampled points
tck = interpolate.splrep(x, y)
print tck
x2 = np.linspace(0, 10, 200)
y2 = interpolate.splev(x2, tck)
# spline with all the middle points as knots (not working yet)
knots = np.asarray(x[1:-1]) # it should be something like this
#knots = np.array([x[1]]) # not working with above line and just seeing what this line does
nknots = 5
idx_knots = (np.arange(1,len(x)-1,(len(x)-2)/np.double(nknots))).astype('int')
knots = x[idx_knots]
print knots
weights = np.concatenate(([1],np.ones(x.shape[0]-2)*.01,[1]))
tck = interpolate.splrep(x, y, t=knots, w=weights)
x3 = np.linspace(0, 10, 200)
y3 = interpolate.splev(x2, tck)
# plot
plt.plot(x, y, 'go', x2, y2, 'b', x3, y3,'r')
plt.show()
似乎可以选择5节,6节给出奇怪的结果,还有更多的错误。
答案 3 :(得分:1)
我刚刚在this link的bézier中找到了我需要的答案。然后我使用代码自己尝试。它显然工作得很好。这是我的实施:
#! /usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import binom
def Bernstein(n, k):
"""Bernstein polynomial.
"""
coeff = binom(n, k)
def _bpoly(x):
return coeff * x ** k * (1 - x) ** (n - k)
return _bpoly
def Bezier(points, num=200):
"""Build Bézier curve from points.
"""
N = len(points)
t = np.linspace(0, 1, num=num)
curve = np.zeros((num, 2))
for ii in range(N):
curve += np.outer(Bernstein(N - 1, ii)(t), points[ii])
return curve
xp = np.array([2,3,4,5])
yp = np.array([2,1,4,0])
x, y = Bezier(list(zip(xp, yp))).T
plt.plot(x,y)
plt.plot(xp,yp,"ro")
plt.plot(xp,yp,"b--")
plt.show()
这个例子的图像。
红点代表控制点。 就是它=)
答案 4 :(得分:0)
您的示例函数是定期的,您需要将per=True
选项添加到interpolate.splrep
方法。
knots = x[1:-1]
weights = np.concatenate(([1],np.ones(x.shape[0]-2)*.01,[1]))
tck = interpolate.splrep(x, y, t=knots, w=weights, per=True)
这给我以下内容:
修改:这也解释了为什么它适用于knots = x[-2:2]
,它是全范围的非定期子集。