簡體   English   中英

組織3d點並通過與位置的距離找到它們

[英]Organize 3d points and found them by distance from a position

我在3D環境中工作。 我在此空間中有一些對象,它們由x,y,z位置表示。

# My objects names (in my real context it's pheromone "point")
A = 1
B = 2
C = 3
D = 4

# My actual way to stock their positions
pheromones_positions = {
    (25, 25, 60): [A, D],
    (10, 90, 30): [B],
    (5, 85, 8): [C]
}

我的目標是找到給定位置附近(隨距離)的點(信息素)。 我這樣做很簡單:

def calc_distance(a, b):
    return sqrt((a[0]-b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2)

def found_in_dict(search, points, distance):
    for point in points:
        if calc_distance(search, point) <= distance:
            return points[point]

founds = found_in_dict((20, 20, 55), pheromones_positions, 10)
# found [1, 4] (A and D)

但是,由於存在大量的信息素,因此非常慢(一個接一個地測試它們...)。 如何組織這些3D位置以更快地找到“距給定位置的距離的位置”? 是否存在可以通過這種方式幫助我的算法或庫(numpy?)?

您應該一次計算所有(平方)距離。 使用NumPy,您可以簡單地從所有位置坐標的(nx3)數組中減去大小為1x3的目標點,並對平方差進行平方和,以獲得包含n個元素的列表:

squaredDistances = np.sum((np.array(pheromones_positions.keys()) - (20, 20, 55))**2, axis=1)
idx = np.where(squaredDistances < 10**2)[0]
print pheromones_positions.values()[idx]

輸出:

[1, 4]

順便說一句:由於return語句在所有點的for循環內,因此它將在找到第一個點后停止迭代。 因此,您可能會錯過第二場或第三場比賽。

暫無
暫無

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

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