numpy 计算投影点坐标

def point_on_line_seg(a, b, p):
    ap = p - a
    ab = b - a
    t = np.dot(ap, ab) / np.dot(ab, ab)
    # if you need the the closest point belonging to the segment
    t = max(0, min(1, t))
    result = a + t * ab
    return result

def point_on_line(a, b, p):
    ap = p - a
    ab = b - a
    t = np.dot(ap, ab) / np.dot(ab, ab)
    result = a +  t* ab
    return result

def np_point_on_line_seg(a,b,p):
    """
    a:n*2
    b:n*2
    p:1*2
    """
    ap = p - a
    ab = b - a
    t = np.sum(np.multiply(ap,ab),axis=1,keepdims=True) / np.sum(np.multiply(ab,ab),axis=1,keepdims=True) 
    # if you need the the closest point belonging to the segment
    t=np.where(t>1,1,t)
    t=np.where(t<0,0,t)
    result = a + np.multiply(t,ab)
    return result 

def np_point_on_line(a,b,p):
    """
    a:n*2
    b:n*2
    p:1*2
    """
    ap = p - a
    ab = b - a
    t = np.sum(np.multiply(ap,ab),axis=1,keepdims=True) / np.sum(np.multiply(ab,ab),axis=1,keepdims=True) 
    result = a + np.multiply(t,ab)
    return result

N=20
low1,high1 = 0,20
low2,high2 = 0,20 
start_points = np.dstack([np.random.uniform(low=low1, high=high1, size=(N,)),np.random.uniform(low=low2, high=high2, size=(N,))])[0]
end_points = np.dstack([np.random.uniform(low=low1, high=high1, size=(N,)),np.random.uniform(low=low2, high=high2, size=(N,))])[0]
target_point = np.dstack([np.random.uniform(low=low1, high=high1, size=(1,)),np.random.uniform(low=low2, high=high2, size=(1,))])[0]
print(start_points.shape)
print(end_points.shape)
print(target_point.shape)
projected_points = np_point_on_line(start_points, end_points, target_point)
for i in range(N):
    P=target_point[0]
    A=start_points[i]
    B=end_points[i]
    projected = projected_points[i]
    x_values = [A[0], B[0]]
    y_values = [A[1], B[1]]

    print(P,projected)
    plt.axis('equal')
    plt.plot(B[0], B[1], 'ro')
    plt.plot(A[0], A[1], 'ro')
    plt.plot(P[0], P[1], 'r+')
    plt.plot(x_values, y_values, 'b-')
    plt.plot(projected[0], projected[1], 'g*')
    plt.show()


posted @ 2021-07-14 15:32  机器狗mo  阅读(426)  评论(0)    收藏  举报