簡體   English   中英

將 (x, y) 坐標投影到直線上作為距離

[英]Project (x, y) coordinates onto a line as a distance

我想將兩個(x,y)點 C 和 E 通常投影到由兩個(x,y)點 A 和 B 定義的線上。我希望投影結果為從 A 到 B 的距離(例如 AD 和 AF 在下圖),而不是作為(x,y)坐標就行了。 請注意 AF 位於 A 到 B 線之外時的負距離。 請幫助我解決以下coordinates_to_distances到距離 function。

通常將點 C 和 E 投影到從 A 到 B 的直線上

import numpy as np

A = np.array([2, 1])   # (x, y) coordinates of A
B = np.array([6, 2])   # (x, y) coordinates of B

x = np.array([3, 1])   # x-coordinates of C and E
y = np.array([3, 2])   # y-coordinates of C and E

def coordinates_to_distances(A, B, x, y):
    # Help
    return distances

distances = coordinates_to_distances(A, B, x, y) # expected result: [1.46, -0.73]

我對您的任務進行了一些修改,以便將點用作字典 ({x, y})。

projectionc的投影點返回到線ab

distance_to_point返回點c到點a 的距離,其中從a的方向由點b給出

注意:當ab線垂直時,示例將不起作用!

import math

def projection(a,b,c):
  n = (b['y'] - a['y']) / (b['x'] - a['x'])
  m = a['y'] - n * a['x']
  p = c['y'] + c['x'] / n
  x = (p - m) / (n + 1 / n)
  y = n * x + m
  return {'x': x, 'y': y}

def distance_to_point(a, b, c):
  dir = 1 if bool(b['x'] > a['x']) == bool(c['x'] > a['x']) else -1
  return math.hypot(c['y'] - a['y'], c['x'] - a['x']) * dir

a = {'x': 2, 'y': 1}  
b = {'x': 6, 'y': 2}  
c = {'x': 3, 'y': 3}
d = projection(a, b, c)
dta = distance_to_point(a, b, d)
print(dta)

NumPy 解決方案:

import numpy as np

A = np.array([2, 1])   # (x, y) coordinates of A
B = np.array([6, 2])   # (x, y) coordinates of B

x = np.array([3, 1])   # x-coordinates of C and E
y = np.array([3, 2])   # y-coordinates of C and E

def coordinates_to_distances(A, B, x, y):
    dy = B[1] - A[1]
    dx = B[0] - A[0]
    x_new, y_new = x * 0 + 1, y * 0 + 1
    if dx == 0:
        x_new, y_new = x * 0 + A[0], y
    if dy == 0:
        x_new, y_new = x, y * 0 + A[1]
    if dx != 0 and dy != 0:
        n = dy / dx
        m = A[1] - n * A[0]
        p = y + x / n
        x_new = (p - m) / (n + 1 / n)
        y_new = n * x_new + m
    dir = x_new * 0 - 1
    dir[(B[0] > A[0]) == (x_new > A[0])] = 1
    return dir * np.sqrt((A[0] - x_new)**2 + (A[1] - y_new)**2)

distances = coordinates_to_distances(A, B, x, y)

print(distances)   # [1.46, -0.73]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM