Created
June 15, 2026 10:22
-
-
Save AndreLester/cc91b25fbfd7839223ebbe4d9fd66540 to your computer and use it in GitHub Desktop.
Calculate the euclidian distance between an array of points to a line segment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def lineseg_dists(p, a, b): | |
| # Handle case where p is a single point, i.e. 1d array. | |
| p = np.atleast_2d(p) | |
| # TODO for you: consider implementing @Eskapp's suggestions | |
| if np.all(a == b): | |
| return np.linalg.norm(p - a, axis=1) | |
| # 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 | |
| x = np.maximum.reduce([s, t, np.zeros(len(p))]) | |
| # perpendicular distance component | |
| # switch to dot-prod method which is dimension-agnostic | |
| y = np.linalg.norm(p - b - t * d) | |
| # use hypot() to improve accuracy | |
| return np.hypot(x, y) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied from Stackoverflow