繁体   English   中英

在Python中以特定参数值查询3D样条曲线上的点

[英]Querying points on a 3D spline at specific parametric values in Python

给定一个定义样条曲线的控制顶点列表,以及查询值列表(0 =行开始,1 =行结束,0.5 =一半,0.25 =四分之一等等)我想找到(尽快)并且尽可能有效地)样条曲线上的那些查询的3D坐标。

我试图找到一些内置的scipy但失败了。 所以我用蛮力方法编写了解决问题的函数:

  1. 将样条细分为n个细分
  2. 加上细分来比较agains查询
  3. 找到每个查询的适当细分步骤并推断一个位置

下面的代码工作正常,但我很想知道是否有更快/更有效的方法来计算我需要的东西,或者更好的东西已经内置的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的其他东西。

遗憾的是,对于您的问题没有一个简单的解决方案,因为它意味着计算三次样条的长度,这并非易事。 但是有一种方法可以使用集成和优化scipy库来简化代码,因此您不必担心精度问题。

首先,您必须了解在引擎盖下, 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:我只是意识到其他东西,你的方法可以在样条曲线之外给出点,而我的方法总是在样条曲线中,取决于你正在做什么这可能很重要

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM