给定一个定义样条曲线的控制顶点列表,以及查询值列表(0 =行开始,1 =行结束,0.5 =一半,0.25 =四分之一,等等...)我想找到(尽可能快速有效地)样条曲线上的那些查询的3D坐标。
我试图找到一些内置的scipy但失败了。所以我用蛮力方法编写了解决问题的函数:
下面的代码工作正常,但我很想知道是否有更快/更有效的方法来计算我需要的东西,或者更好的是已经内置的scipy我可能错过了。
这是我的功能:
import numpy as np
import scipy.interpolate as interpolate
def uQuery(cv,u,steps=100,projection=True):
''' Brute force point query on spline
cv = list of spline control vertices
u = list of queries (0-1)
steps = number of curve subdivisions (higher value = more precise result)
projection = method by wich we get the final result
- True : project a query onto closest spline segments.
this gives good results but requires a high step count
- False: modulates the parametric samples and recomputes new curve with splev.
this can give better results with fewer samples.
definitely works better (and cheaper) when dealing with b-splines (not in this examples)
'''
u = np.clip(u,0,1) # Clip u queries between 0 and 1
# Create spline points
samples = np.linspace(0,1,steps)
tck,u_=interpolate.splprep(cv.T,s=0.0)
p = np.array(interpolate.splev(samples,tck)).T
# at first i thought that passing my query list to splev instead
# of np.linspace would do the trick, but apparently not.
# Approximate spline length by adding all the segments
p_= np.diff(p,axis=0) # get distances between segments
m = np.sqrt((p_*p_).sum(axis=1)) # segment magnitudes
s = np.cumsum(m) # cumulative summation of magnitudes
s/=s[-1] # normalize distances using its total length
# Find closest index boundaries
s = np.insert(s,0,0) # prepend with 0 for proper index matching
i0 = (s.searchsorted(u,side='left')-1).clip(min=0) # Find closest lowest boundary position
i1 = i0+1 # upper boundary will be the next up
# Return projection on segments for each query
if projection:
return ((p[i1]-p[i0])*((u-s[i0])/(s[i1]-s[i0]))[:,None])+p[i0]
# Else, modulate parametric samples and and pass back to splev
mod = (((u-s[i0])/(s[i1]-s[i0]))/steps)+samples[i0]
return np.array(interpolate.splev(mod,tck)).T
这是一个用法示例:
import matplotlib.pyplot as plt
cv = np.array([[ 50., 25., 0.],
[ 59., 12., 0.],
[ 50., 10., 0.],
[ 57., 2., 0.],
[ 40., 4., 0.],
[ 40., 14., 0.]])
# Lets plot a few queries
u = [0.,0.2,0.3,0.5,1.0]
steps = 10000 # The more subdivisions the better
x,y,z = uQuery(cv,u,steps).T
fig, ax = plt.subplots()
ax.plot(x, y, 'bo')
for i, txt in enumerate(u):
ax.annotate(' u=%s'%txt, (x[i],y[i]))
# Plot the curve we're sampling
tck,u_=interpolate.splprep(cv.T,s=0.0)
x,y,z = np.array(interpolate.splev(np.linspace(0,1,1000),tck))
plt.plot(x,y,'k-',label='Curve')
# Plot control points
p = cv.T
plt.scatter(p[0],p[1],s=80, facecolors='none', edgecolors='r',label='Control Points')
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()
答案 0 :(得分:1)
对不起我以前的评论,我误解了这个问题。
请注意,我将您的查询称为w = [0.,0.2,0.3,0.5,1.0]
,因为我将u
用于其他内容。
首先你必须明白,splprep
创建了一个形状为x = Fx(u)和y = Fy(u)的三次样条曲线,其中u
是0的参数到1,但与样条曲线的长度不是线性相关的,例如对于此控制点:
cv = np.array([[ 0., 0., 0.],
[ 100, 25, 0.],
[ 0., 50., 0.],
[ 100, 75, 0.],
[ 0., 100., 0.]])
您可以看到参数u
的行为方式。值得注意的是,您可以为控制点定义所需的u
值,这会对样条曲线的形状产生影响。
现在,当您致电splev
时,您确实要求给定u
参数的样条线坐标。因此,为了完成您想要做的事情,您需要找到样条曲线长度的给定部分的u
。
首先,为了获得样条曲线的总长度,你可以做的不多,但是像你一样进行数值积分,但你可以使用scipy的集成库来更容易。
import scipy.integrate as integrate
def foo(u):
xx,yy,zz=interpolate.splev(u,tck,der=1)
return (xx**2 + yy**2)**0.5
total_length=integrate.quad(foo,0,1)[0]
一旦获得样条曲线的总长度,就可以使用optimize
库找到u
的值,该值将整合到所需长度的分数。将此desired_u
用于splev
将为您提供所需的坐标。
import scipy.optimize as optimize
desired_u=optimize.fsolve(lambda uu: integrate.quad(foo,0,uu)[0]-w*total_length,0)[0]
x,y,z = np.array(interpolate.splev(desired_u,tck))
编辑:我测量了我的方法与你的方法的性能,而你的方法更快,也更精确,唯一最差的指标是内存分配。我找到了一种方法来加速我的方法,仍然使用低内存分配,但它牺牲了精度。
我将使用100个查询点作为测试。
我的方法现在就是:
time = 21.686723 s
memory allocation = 122.880 kb
我将使用我的方法给出的点作为真实坐标,并测量每种方法与这些方法之间100点的平均距离
现在的方法:
time = 0.008699 s
memory allocation = 1,187.840 kb
Average distance = 1.74857994144e-06
通过不对每个点的积分使用fsolve
,但是通过从点的样本创建插值函数u=F(w)
,然后使用该函数,可以提高方法的速度,这会快得多。
import scipy.interpolate as interpolate
import scipy.integrate as integrate
def foo(u):
xx,yy,zz=interpolate.splev(u,tck,der=1)
return (xx**2 + yy**2)**0.5
total_length=integrate.quad(foo,0,1)[0]
yu=[integrate.quad(foo,0,uu)[0]/total for uu in np.linspace(0,1,50)]
find_u=interpolate.interp1d(yu,np.linspace(0,1,50))
x,y,z=interpolate.splev(find_u(w),tck)
我得到50个样本:
time = 1.280629 s
memory allocation = 20.480 kb
Average distance = 0.226036973904
这比以前快得多,但仍然没有你的那么快,精度也不如你的好,但在内存方面要好得多。但这取决于你的样本数量。
你的方法有1000分和100分:
1000 points
time = 0.002354 s
memory allocation = 167.936 kb
Average distance = 0.000176413655938
100 points
time = 0.001641 s
memory allocation = 61.440 kb
Average distance = 0.0179918600812
我的方法有20和100个样本
20 samples
time = 0.514241 s
memory allocation = 14.384 kb
Average distance = 1.42356341648
100 samples
time = 2.45364 s
memory allocation = 24.576 kb
Average distance = 0.0506075927139
考虑到所有事情,我认为你的方法在所需精度的正确点数上更好,我的代码行数更少。
编辑2:我只是意识到其他的东西,你的方法可以在样条曲线之外给出点,而我的方法总是在样条曲线中,这取决于你正在做什么这可能很重要