计算到多个点的最小距离的地图

时间:2015-08-08 22:37:15

标签: python algorithm math numpy computational-geometry

给定一个点列表obstacles(以row, column矩阵坐标列表的形式给出,形状为(n, 2)的ndarray),返回一个大小为size的地图(其中) size是2D NumPy数组的形状,其中r, c的值是到最近的"障碍的欧几里德距离。"

def gen_distgrid(size, obstacles):
    n_obstacles = obstacles.shape[0]
    distgrids = np.zeros((n_obstacles + 4, size[0], size[1]))
    for layer in range(n_obstacles):
        for i in range(size[0]):
            for j in range(size[1]):
                distgrids[layer, i, j] = np.linalg.norm(obstacles[layer,:] - [i,j])
    for i in range(size[0]):
            for j in range(size[1]):
                distgrids[n_obstacles + 0, i, j] = i
                distgrids[n_obstacles + 1, i, j] = (size[0] - i)
                distgrids[n_obstacles + 2, i, j] = j
                distgrids[n_obstacles + 3, i, j] = (size[1] - j)
    distgrid = np.min(distgrids, axis=0)
    return distgrid

我的方法非常慢,我觉得应该有更好的方法。

2 个答案:

答案 0 :(得分:0)

Here是使用Numpy和SciPy的KD树解决类似问题的方法。只需将障碍物插入KD树并查询每个网格点的树以获得最近的邻居。

答案 1 :(得分:0)

我最终使用了SciPy的a KD-tree。它具有非常容易的距离功能。

from scipy.spatial import cKDTree as KDTree
def gen_distgrid(obstacles):
    n_obstacles = obstacles.shape[0]
    obstacles = np.vstack((obstacles, [0,0], [0, size[1] - 1], [size[0] - 1, 0], [size[0] - 1, size[1] - 1]))

    distgrid = np.zeros((size[0], size[1]))
    obs_tree = KDTree(data=obstacles)

    i_v = np.arange(size[0])
    j_v = np.arange(size[1])

    coordmat = np.dstack(np.meshgrid(i_v, j_v, indexing='ij'))
    obs_dists, obs_locs = obs_tree.query(coordmat)

    top_dists = np.repeat(i_v, size[1]).reshape(size)
    bottom_dists = np.repeat(size[0] - i_v, size[1]).reshape(size)
    left_dists = np.repeat(j_v, size[0]).reshape(np.transpose(size)).T
    right_dists = np.repeat(size[1] - j_v, size[0]).reshape(np.transpose(size)).T

    dists = np.min([obs_dists, top_dists, bottom_dists, left_dists, right_dists], axis=0)
    return dists