首页 > 解决方案 > 3d中从点到线段的距离(Python)

问题描述

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

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

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

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

标签: python3ddistanceline-segment

解决方案


这个答案改编自这里: Calculate the euclidian distance between a array of points to a line segment in Python without for loop

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

推荐阅读