I'm looking for a python implementation of the shortest distance between a point and a line segment in 3D and the intersection point on the segment
0
votes
1 Answers
1
votes
Here's an implemenation using 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))
Explanation
Given a segment, identified by two points xa
and xb
, and a generic point p
. We define the following quantities
A generic point on the segment, has coordinates:
So the distance of the point p
from a generic point on the segment is:
We want to minimize the squared distance (we use the squared distance to make calculations a bit easier)
i.e.
This gives us the value of t
that minimizes the distance (actually makes stationary).
Now we need to remember that we are constrained to keep , so we can clamp t
.
Computing d(t_min)
will gives the minimum distance.
The distance will be the norm of the returned d
: np.linalg.norm(d)
or, equivalently, np.sqrt(d.dot(d))
.