Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Projected Point location (x,y) on given line start(x,y) end(x,y)

Tags:

python

numpy

If i have three points P1, P2, P3 with their coordinates(x,y)

P1(x,y) and P3(x,y) are coordinate of line(start, end) and P3 is a point need to be projected.

how can i find the coordinate of point r(x,y) which is projection of P3 over P1 and P2 enter image description here

like image 519
MSallal Avatar asked Mar 02 '23 13:03

MSallal


1 Answers

This solution extends to points with any geometric dimensions (2D, 3D, 4D, ...). It assumes all points are one dimensional numpy arrays (or two dimensional with one dimension shape 1). I am not sure if you require the projection to fall onto line segment or the extension of segment so I include both. You can pick whichever fits your question the best:

#distance between p1 and p2
l2 = np.sum((p1-p2)**2)
if l2 == 0:
  print('p1 and p2 are the same points')

#The line extending the segment is parameterized as p1 + t (p2 - p1).
#The projection falls where t = [(p3-p1) . (p2-p1)] / |p2-p1|^2

#if you need the point to project on line extention connecting p1 and p2
t = np.sum((p3 - p1) * (p2 - p1)) / l2

#if you need to ignore if p3 does not project onto line segment
if t > 1 or t < 0:
  print('p3 does not project onto p1-p2 line segment')

#if you need the point to project on line segment between p1 and p2 or closest point of the line segment
t = max(0, min(1, np.sum((p3 - p1) * (p2 - p1)) / l2))

projection = p1 + t * (p2 - p1)
like image 161
Ehsan Avatar answered Apr 27 '23 06:04

Ehsan