[英]Distance from a point to a line segment in 3d (Python)
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). 我正在寻找Python函数,该函数将计算3D点(x_0,y_0,z_0)到其端点(x_1,y_1,z_1)和(x_2,y_2,z_2)定义的线段的距离。
I have only found solution for 2D for this problem. 我只找到针对此问题的2D解决方案。
There are solutions to finding a distance from a point to a line in 3d, but not to a line segment, like here: 有一些解决方案可以在3d中找到从点到线的距离,而不是到线段的距离,例如:
(picture taken from Calculate distance point to line segment with special cases ) (图片来自“ 计算距离点到线段的特殊情况” )
This answer is adapted from here: Calculate the euclidian distance between an array of points to a line segment in Python without for loop . 答案是从这里改编的: 在没有for循环的情况下,在Python中计算点数组到线段之间的欧几里得距离 。
Function lineseg_dist
returns the distance the distance from point p to line segment [a,b]. 函数lineseg_dist
返回从点p到线段[a,b]的距离。 p
, a
and b
are np.arrays. 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.