3d 中点到线段的距离 (Python)

San*_*kar 5 python 3d distance line-segment

我正在寻找Python函数,它可以计算从3D中的点(x_0,y_0,z_0)到由其端点(x_1,y_1,z_1)和(x_2,y_2,z_2)定义的线段的距离。

我只找到了这个问题的 2D 解决方案。

有一些解决方案可以找到 3d 中点到线的距离,但不能找到线段的距离,如下所示: 距离到分段

(图片取自特殊情况下计算点到线段的距离

San*_*kar 5

这个答案改编自这里: Calculate the euclidian distance between an array ofpoints to a lineegment in Python without forloop

函数lineseg_dist返回点 p 到线段 [a,b] 的距离。pa并且b是 np.arrays。

import numpy as np

def lineseg_dist(p, a, b):

    # normalized tangent vector
    d = np.divide(b - a, np.linalg.norm(b - a))

    # signed parallel distance components
    s = np.dot(a - p, d)
    t = np.dot(p - b, d)

    # clamped parallel distance
    h = np.maximum.reduce([s, t, 0])

    # perpendicular distance component
    c = np.cross(p - a, d)

    return np.hypot(h, np.linalg.norm(c))
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“p、a、b”是*数组的数组*(即点数组)。对于您的问题,您可能希望使用一组点,在这种情况下,“s”和“t”将是标量 - 因此“np.zeros(len(p))”需要与“0”一起放置。是的,如果您可以保证“a”永远不等于“b”,那么“np.all”检查是不必要的 (2认同)