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

时间:2019-06-05 15:17:44

标签: 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中找到从点到线的距离,而不是到线段的距离,例如: dist to segment

(图片来自Calculate distance point to line segment with special cases

1 个答案:

答案 0 :(得分:1)

此答案改编自此处: Calculate the euclidian distance between an array of points to a line segment in Python without for loop

函数lineseg_dist返回从点p到线段[a,b]的距离。 pab是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))