我有一个数组,它描述了一条折线(连接直线段的有序列表),如下所示:
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))
相反,我想使用一些 native Scipy/Numpy 函数来应用单个函数调用,没有循环。
我能得到的最接近的是:
from scipy.spatial.distance import pdist
segdists = pdist(points, metric='euclidean')
但在后一种情况下,segdists 提供了每个距离,我只想获取相邻行之间的距离。
此外,我宁愿避免创建自定义函数(因为我已经有了一个可行的解决方案),而是更多地使用原生函数的“numpythonic”。
最佳答案
这是一种方法:
使用向量化的 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))
关于python - 使用numpy计算数组连续点之间的欧氏距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590484/