簡體   English   中英

如何計算數組中 3D 坐標的距離

[英]How to calculate distances in 3D coordinates in an array

我正在嘗試計算點之間的初始和后續距離。 我得到的數據是一個 csv,其中每三列對應一個 LED 標記。 即第 1 列是標記 1 的 x 坐標,第 2 列是標記 1 的 y 坐標,第 3 列是標記 1 ets 的 z 坐標。 每行對應於記錄位置的時間。 我很難找出組織數據的最佳方式,以便我可以使用它。 我需要 a) 在時間 0 處找到標記之間的初始位置和初始距離,並且 b) 在不同時間找到標記之間距離的任何變化。

我最初將所有 x 坐標放在一個數組中,將所有 y 坐標放在一個數組中,將所有 z 坐標放在一個數組中,但意識到我不能(不知道如何?)遍歷數組,所以我可以找到相鄰點之間的差異。 IE。 標記 1 和標記 2 之間的距離是 sqrt((x2-x1)**2+(y2-y1)**2+(z2-z1)**2) 但由於 x2 和 x1 在同一個數組中不能' t(不知道如何?)來迭代所有 xs(分別是 ys 和 zs)之間的差異。 在下面的代碼中,我轉置了數組,以便我可以遍歷行(而不是列)

for i in range(m): #where m is the number of markers
    x_diff= x_array[i+1]-x_array[i]
    y_diff=y_array[i+1]-y_array[i]
    z_diff=z_array[i+1]-z_array[i]
    dist=np.sqrt(x_diff**2+y_diff**2+z_diff**2)

我想要一個數組,其中每一列都是相鄰標記之間的歐幾里德距離,而行對應於每次的距離。

您可以將 SciPy 的pdist函數用於成對距離。 例如,

>>> X
array([[1, 2, 3],
       [1, 2, 3],
       [4, 0, 0]])
>>> from scipy.spatial.distance import pdist
>>> pdist(X)
array([0.        , 4.69041576, 4.69041576])

距離以對 (0,1)、(0,2)、(1,2) 的形式輸出。

以下是從像原始 csv 一樣布局的數組開始的分步說明:

# 2 time points, 4 markers, values between 0 and 8
csv = np.random.randint(0,9,(2,12))
csv
# array([[8, 5, 3, 2, 3, 2, 2, 5, 6, 8, 2, 4],
#        [8, 2, 7, 4, 7, 7, 8, 0, 3, 0, 2, 4]])

# reshape to get x,y,z aligned
m,n = csv.shape
xyz = csv.reshape(m,-1,3)
xyz
# array([[[8, 5, 3],
#         [2, 3, 2],
#         [2, 5, 6],
#         [8, 2, 4]],
#
#        [[8, 2, 7],
#         [4, 7, 7],
#         [8, 0, 3],
#         [0, 2, 4]]])

# get coordinate-wise differences between adjacent markers
dist_1d = np.diff(xyz,axis=1)
dist_1d
# array([[[-6, -2, -1],
#         [ 0,  2,  4],
#         [ 6, -3, -2]],
#
#        [[-4,  5,  0],
#         [ 4, -7, -4],
#         [-8,  2,  1]]])

# compute squared Euclidean distance
# (you could take the square root of that but if you are
# only interested in changes it doesn't seem necessary)
eucl2 = (dist_1d*dist_1d).sum(axis=2)
eucl2
# array([[41, 20, 49],
#        [41, 81, 69]])

您需要將該 2d 數組轉換為 3d 數組。

rows, cols = csv.shape
csv_3d = csv.reshape(rows, -1, 3)

然后np.diff沿第二個軸(點之間)

del_csv_3d = np.diff(csv_3d, axis = 1)

然后沿最后一個軸取范數

out = np.linalg.norm(del_csv_3d , axis = -1)

這應該是您需要的數據。

暫無
暫無

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

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