我正在寻找3D中点与线段之间的最短距离与线段上的相交点的python实现
numpy
的实现:def min_distance(r: np.ndarray, a: np.ndarray):
""" Compute the minimal distance between a point and a segment.
Given a segment of points xa and xb and a point p
Parameters
----------
r
xb - xa
a
xa - p
Returns
-------
d
The minimal distance spanning from p to the segment
"""
min_t = np.clip(-a.dot(r) / (r.dot(r)), 0, 1)
d = a + min_t * r
return np.sqrt(d.dot(d))
说明
给出一个段,该段由两个点xa
和xb
以及一个通用点p
标识。我们定义以下数量段上的通用点,具有坐标:
因此,点
p
与线段上通用点的距离为:我们希望最小化平方距离(我们使用平方距离使计算更容易一些)
即
这为我们提供了使距离最小化(实际上使静止)的
t
值。现在,我们需要记住,我们必须保持 0“,因此可以钳位[]。
计算
t
将给出最小距离。该距离将是返回的
d(t_min)
:d
或等价的np.linalg.norm(d)
的范数。
np.sqrt(d.dot(d))