簡體   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