在Python中以特定参数值查询三维样条曲线上的点
给定定义样条曲线的控制点列表和查询值列表(0=线开始,1=线结束,0.5=一半,0.25=四分之一,等等),我希望(尽可能快速有效地)找到样条曲线上这些查询的三维坐标 我试图找到一些内置的scipy,但失败了。因此,我编写了一个函数,用蛮力方法解决这个问题:在Python中以特定参数值查询三维样条曲线上的点,python,numpy,scipy,spline,Python,Numpy,Scipy,Spline,给定定义样条曲线的控制点列表和查询值列表(0=线开始,1=线结束,0.5=一半,0.25=四分之一,等等),我希望(尽可能快速有效地)找到样条曲线上这些查询的三维坐标 我试图找到一些内置的scipy,但失败了。因此,我编写了一个函数,用蛮力方法解决这个问题: 将样条曲线细分为n个细分 添加细分以比较agains查询 为每个查询找到适当的细分步骤并推断位置 下面的代码工作得很好,但我想知道是否有更快/更有效的方法来计算我所需要的,或者更好的是,我可能错过了一些已经内置在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()
结果是:
很抱歉我之前的评论,我误解了这个问题 请注意,我将您的查询称为
w=[0,0.2,0.3,0.5,1.0]
,因为我使用u
来表示其他内容
遗憾的是,您的问题没有简单的解决方案,因为它意味着计算三次样条曲线的长度,而这并不是一件小事。但是有一种方法可以使用integrate和optimizescipy库简化代码,这样您就不必担心精度问题
首先,您必须了解,在发动机罩下,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
time = 0.008699 s
memory allocation = 1,187.840 kb
Average distance = 1.74857994144e-06
我将使用我的方法给出的点作为真实坐标,并测量每个方法和这些方法之间100个点的平均距离
您当前的方法:
time = 21.686723 s
memory allocation = 122.880 kb
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:我刚刚意识到,你的方法可以在样条线之外给出点,而我的方法总是在样条线中,这取决于你在做什么,这可能很重要感谢所有的澄清!我从你的解释中学到了很多,我真的很感激!我把你的答案写进了一个函数,用我的答案来测试它。你给了我一个更精确的结果,但运行起来要昂贵得多。对于5个查询,0.002s比0.495s。对于100个查询,我的方法没有受到影响,但您的方法使用了11.568秒,这是一个非常显著的差异。所以它不符合我的速度标准,但它确实更简单。哇,我知道会有不同,但我没想到会有这么多。我猜罪魁祸首是
fsolve
,我会看看我能不能加快速度。如果我发现了什么,我会告诉你的是的,一个样本的F解需要0.140秒。顺便说一句,因为你似乎知道很多关于样条曲线,如果你能给我你的意见,我将非常感谢!很抱歉回复晚了,我周末出去了。我将编辑我的答案,包括时间和内存分配的基准测试。还有如何加速我的方法。但是tl;你的方法更好。