Numpy:找到沿着

时间:2015-07-08 09:49:41

标签: numpy interpolation

我在2D空间中有一堆点,它们都位于一条线(多边形)上。如何计算线上这些点的平均坐标?

我不是指2D空间中点的质心(正如@rth最初在answer中提出的那样),而是指沿着它们所在线的点的平均位置。所以基本上,我可以将线转换为1D轴,计算1D中的平均位置,并将平均值的位置转换回2D空间。

也许这些都是必要的步骤,但我认为(或希望)numpy / scipy中有一个函数允许我一步完成。

2 个答案:

答案 0 :(得分:1)

编辑:您在问题中描述的方法确实可能是解决此问题的最简单方法。

这是一个实现,计算沿1D线的顶点位置,取其平均值,最后用参数插值计算相应的2D位置,

import numpy as np
from scipy.interpolate import splprep, splev

vert = np.random.randn(1000, 2) # vertices definition here

# calculate the Euclidean distances between consecutive vertices
# equivalent to a for loop with
# dl[i] = ((vert[i+1, 0] - vert[i, 0])**2 + (vert[i+1,1] - vert[i,1])**2)**0.5
dl = (np.diff(vert, axis=0)**2).sum(axis=1)**0.5 

# pad with 0, so dl.shape[0] == vert.shape[0] for convenience
dl = np.insert(dl, 0, 0.0)
l = np.cumsum(dl) # 1D coordinates along the line
l_mean = np.mean(l) # mean in the line coordinates

# calculate the coordinate of l_mean in 2D space
# with parametric B-spline interpolation
tck, _ = splprep(x=vert.T,  u=l, k=3)
res = splev(l_mean, tck)
print(res)

Edit2 :现在假设您的路径vert_full和一些近似测量vert_1vert_2等具有高分辨率的点数,那么你能做的就是以下几点。

  • vert_1等的每个点投射到确切的路径上。假设vert_full的数据点数比vert_1多得多,我们只需在vert_1中查找vert_full的最近邻居:

    from scipy.spatial import cKDTree
    tr = cKDTree(vert_full)
    d, idx = tr.query(vert_1, k=1)
    vert_1_proj = vert_full[idx] # this gives the projected corrdinates onto vert_full
    # I have not actually run this, so it might require minor changes
    
  • 将上述平均值计算与新的vert_1_proj向量一起使用。

答案 1 :(得分:1)

与此同时,我找到了问题的答案,尽管使用的是Shapely而不是Numpy。

from shapely.geometry import LineString, Point

# lists of points as (x,y) tuples
path_xy = [...]
points_xy = [...] # should be on or near path

path = LineString(path_xy)            # create path object
pts = [Point(p) for p in points_xy]   # create point objects
dist = [path.project(p) for p in pts] # distances along path
mean_dist = np.mean(dist)             # mean distance along path
mean = path.interpolate(mean_dist)    # mean point

mean_xy = (mean.x,mean.y)

这完美无缺!

(这也是为什么我必须接受它作为答案,尽管我非常感谢@rth的帮助!)