Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance between point and a line (from two points)

I'm using Python+Numpy (can maybe also use Scipy) and have three 2D points

(P1, P2, P3); 

I am trying to get the distance from P3 perpendicular to a line drawn between P1 and P2. Let P1=(x1,y1), P2=(x2,y2) and P3=(x3,y3)

In vector notation this would be pretty easy, but I'm fairly new to python/numpy and can't get anythng that works (or even close).

Any tips appreciated, thanks!

like image 665
user1185675 Avatar asked Oct 03 '16 20:10

user1185675


People also ask

What is the distance between a line and a point lying on it?

The distance of point from a line, 'd' is the length of the perpendicular drawn from N to l. The x and y-intercepts are −C/A and −C/B respectively. NM = d = |Ax1 + By1 + C| / (A2 + B2)½. It is interesting to find out the distance between two parallel lines.


3 Answers

Try using the norm function from numpy.linalg

d = norm(np.cross(p2-p1, p1-p3))/norm(p2-p1)
like image 115
DotPi Avatar answered Oct 06 '22 12:10

DotPi


np.cross returns the z-coordinate of the cross product only for 2D vectors. So the first norm in the accepted answer is not needed, and is actually dangerous if p3 is an array of vectors rather than a single vector. Best just to use

d=np.cross(p2-p1,p3-p1)/norm(p2-p1)

which for an array of points p3 will give you an array of distances from the line.

like image 32
Martin Hardcastle Avatar answered Oct 06 '22 11:10

Martin Hardcastle


For the above-mentioned answers to work, the points need to be numpy arrays, here's a working example:

import numpy as np
p1=np.array([0,0])
p2=np.array([10,10])
p3=np.array([5,7])
d=np.cross(p2-p1,p3-p1)/np.linalg.norm(p2-p1)
like image 11
Szymon Szott Avatar answered Oct 06 '22 11:10

Szymon Szott