python3ddistanceline-segment

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).

I have only found solution for 2D for this problem.

There are solutions to finding a distance from a point to a line in 3d, but not to a line segment, like here: dist to segment

(picture taken from Calculate distance point to line segment with special cases)


Solution

  • This answer is adapted from here: Calculate the euclidian distance between an array of points to a line segment in Python without for loop.

    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))