【问题标题】:Calculating euclidean distance between consecutive points of an array with numpy用numpy计算数组的连续点之间的欧几里得距离
【发布时间】:2012-11-15 10:37:56
【问题描述】:

我有一个数组,它描述了一条折线(连接的直线段的有序列表),如下所示:

points = ((0,0),
          (1,2),
          (3,4),
          (6,5),
          (10,3),
          (15,4))
points = numpy.array(points, dtype=float)

目前,我使用以下循环获取分段距离列表:

segdists = []
for seg in xrange(points.shape[0]-1):
    seg = numpy.diff(points[seg:seg+2], axis=0)
    segdists.append(numpy.linalg.norm(seg))

相反,我想使用一些本机 Scipy/Numpy 函数来应用一个没有循环的函数调用。

我能得到的最接近的是:

from scipy.spatial.distance import pdist
segdists = pdist(points, metric='euclidean')

但在后一种情况下,segdists 提供了每个距离,我只想获取相邻行之间的距离。

另外,我宁愿避免创建自定义函数(因为我已经有了一个可行的解决方案),而是使用更多的“numpythonic”原生函数。

【问题讨论】:

    标签: python numpy scipy euclidean-distance


    【解决方案1】:

    这是一种方法:

    使用矢量化的np.diff 计算增量:

    d = np.diff(points, axis=0)
    

    然后使用np.hypot 计算长度:

    segdists = np.hypot(d[:,0], d[:,1])
    

    或者使用更明确的计算:

    segdists = np.sqrt((d ** 2).sum(axis=1))
    

    【讨论】:

    • 我自己搞了一些死胡同,你这么说其实很简单。我之前看到过 hypot 被提及,但谷歌搜索“numpy hypot”没有返回任何内容,我不得不在 numpy 文档页面上进行搜索。谢谢!
    • 这在 3D 中也可以吗?
    • @Varlor:不是hypot,而是第二个版本segdists = np.sqrt((d ** 2).sum(axis=1)),在3D中工作。
    猜你喜欢
    • 2014-06-09
    • 2015-09-23
    • 2013-08-22
    • 2019-02-24
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    相关资源
    最近更新 更多