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

查看:130
本文介绍了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]的距离. p a b 是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天全站免登陆