0
votes

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

1
What about scipy?rdbisme
@DiTTiD No, this was an answer for point to point interdistance. I need an implementation for point to line segment distance as mentioned in the titleuser7924113

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

r

A generic point on the segment, has coordinates:

x

So the distance of the point p from a generic point on the segment is:

d

We want to minimize the squared distance (we use the squared distance to make calculations a bit easier)

dd

dd2

i.e.

ddt

This gives us the value of t that minimizes the distance (actually makes stationary).

enter image description here

Now we need to remember that we are constrained to keep t01, 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)).

figure1

enter image description here