1 点和线段的参数
# 点的坐标
p = [0,0]
# 线段的参数
# 线段的端点1
a = [-1,1]
# 线段的端点2
b = [1,1]
2 求取距离
import numpy as np
def dis_point_to_seg_line(p, a, b):
a, b, p = np.array(a), np.array(b), np.array(p) # trans to np.array
d = np.divide(b - a, np.linalg.norm(b - a)) # normalized tangent vector
s = np.dot(a - p, d) # signed parallel distance components
t = np.dot(p - b, d)
h = np.maximum.reduce([s, t, 0]) # clamped parallel distance
c = np.cross(p - a, d) # perpendicular distance component
return np.hypot(h, np.linalg.norm(c))
print(dis_point_to_seg_line(p,a,b))
3 结果
>>> 0.7071067811865475