Distance between point and a line (from two points)

落爺英雄遲暮 提交于 2019-12-17 10:52:14

问题


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!


回答1:


Try using the norm function from numpy.linalg

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



回答2:


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.




回答3:


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)



回答4:


abs((x2-x1)*(y1-y0) - (x1-x0)*(y2-y1)) / np.sqrt(np.square(x2-x1) + np.square(y2-y1))

Can be used directly through the formula, just have to plug in the values and boom it will work.




回答5:


To find distance to line from point if you have slope and intercept you can use formula from wiki https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line Python:

def distance(point,coef):
    return abs((coef[0]*point[0])-point[1]+coef[1])/math.sqrt((coef[0]*coef[0])+1)

coef is a tuple with slope and intercept




回答6:


Shortest Distance from Point to a Line

This is the code I got from https://www.geeksforgeeks.org:

import math 

# Function to find distance 
def shortest_distance(x1, y1, a, b, c):    
    d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b)) 
    print("Perpendicular distance is", d)

Now you have to find A, B, C, x, and y.

import numpy as np
closest = []
x = (x ,y)
y = (x, y)
coef = np.polyfit(x, y, 1)
A = coef[0]
B = coef[1]
C = A*x[0] + B*x[1]

Now you can plug in the values:

shortest_dis = shortest_distance(x, y, A, B, C)

The full code may look like this:

import math
import numpy as np

def shortest_distance(x1, y1, a, b, c):    
    d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b)) 
    print("Perpendicular distance is", d)

closest = []
x = (x ,y)
y = (x, y)
coef = np.polyfit(x, y, 1)
A = coef[0]
B = coef[1]
C = A*x[0] + B*x[1]
shortest_dis = shortest_distance(x, y, A, B, C)

Please let me know if any of this is unclear.



来源:https://stackoverflow.com/questions/39840030/distance-between-point-and-a-line-from-two-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!