从点到 3d 中的线段的距离(Python) [英] Distance from a point to a line segment in 3d (Python)

查看:22
本文介绍了从点到 3d 中的线段的距离(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking for Python function that would compute distance from a point in 3D (x_0,y_0,z_0) to a line segment defined by its endpoints (x_1,y_1,z_1) and (x_2,y_2,z_2).

对于这个问题,我只找到了 2D 的解决方案.

I have only found solution for 2D for this problem.

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

There are solutions to finding a distance from a point to a line in 3d, but not to a line segment, like here:

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

推荐答案

此答案改编自此处:在没有for循环的情况下,在Python中计算点数组到线段之间的欧几里德距离.

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

Function lineseg_dist returns the distance the distance from point p to line segment [a,b]. p, a and b are 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))

这篇关于从点到 3d 中的线段的距离(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆