【问题标题】:Find all points within distance 1 of specific point in 2D numpy matrix查找二维numpy矩阵中特定点距离1内的所有点
【发布时间】:2018-10-21 22:33:07
【问题描述】:

我想在我的 numpy 矩阵中的某个点的范围 1(或正好对角线)内找到一个点列表

例如说我的矩阵m 是:

[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 1 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]] 

我想获得一个元组列表或代表以下 X 的 9 个点的所有坐标的东西:

[[0 0 0 0 0]
 [0 X X X 0]
 [0 X X X 0]
 [0 X X X 0]
 [0 0 0 0 0]]

这是另一个目标点位于边缘的示例:

[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 1]
 [0 0 0 0 0]
 [0 0 0 0 0]] 

在这种情况下,目标点的距离 1 内只有 6 个点:

[[0 0 0 0 0]
 [0 0 0 X X]
 [0 0 0 X X]
 [0 0 0 X X]
 [0 0 0 0 0]] 

编辑:

假设我知道目标点的坐标,使用 David Herrings 关于切比雪夫距离的回答/评论是我尝试解决上面的示例 2:

from scipy.spatial import distance

point = [2, 4]
valid_points = []
for x in range(5):
  for y in range(5):
    if(distance.chebyshev(point, [x,y]) <= 1):
      valid_points.append([x,y])

print(valid_points) # [[1, 3], [1, 4], [2, 3], [2, 4], [3, 3], [3, 4]]

这对于更大的数组来说似乎有点低效,因为我只需要检查一小部分单元格,而不是整个矩阵。

【问题讨论】:

  • 距离是切比雪夫距离,也称为国王度量(来自国际象棋)。

标签: python numpy scipy scipy-spatial


【解决方案1】:

我认为你让它有点太复杂了——不需要依赖复杂的函数

import numpy as np

# set up matrix
x = np.zeros((5,5))
# add a single point
x[2,-1] = 1 

# get coordinates of point as array
r, c = np.where(x)
# convert to python scalars
r = r[0]
c = c[0]
# get boundaries of array
m, n = x.shape

coords = []
# loop over possible locations
for i in [-1, 0, 1]: 
    for j in [-1, 0, 1]: 
        # check if location is within boundary
        if 0 <= r + i < m and 0 <= c + j < n:
            coords.append((r + i, c + j)) 

print(coords)

>>> [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]

【讨论】:

  • 我不知道where 的那个应用程序。整洁!
【解决方案2】:

这里没有感兴趣的算法。如果你还不知道 1 在哪里,首先你必须找到它,你最好的办法就是搜索每个元素。 (您可以numpy 使用argmax 以C 速度执行此操作,从而获得恒定因子的加速;使用divmod 将展平的索引分成行和列。)此后,所有你要做的是将 &pm;1(或 0)添加到坐标中,除非它会将您带到数组边界之外。您永远不会构建坐标只是为了以后丢弃它们。

【讨论】:

  • 我需要使用有效坐标的数量来计算概率(我需要分配每个有效坐标 0.9/num_valid_coordinates)并且我需要分配其余坐标(无效的坐标)在矩阵中:0.1/num_non_valid_coordinates)。
  • @simonsaysgetlit:然后你想找到坐标,计算邻域(在足够大的网格上总是 4、6 或 9),然后形成概率。最后一个可以通过广播轻松完成 - 您想将其编辑到您的问题中吗?
【解决方案3】:

一种简单的方法是使用笛卡尔积获取所有可能的坐标

设置数据:

x = np.array([[0,0,0], [0,1,0], [0,0,0]])
x
array([[0, 0, 0],
       [0, 1, 0],
       [0, 0, 0]])

您知道坐标将是您所在位置的 +/- 1:

loc = np.argwhere(x == 1)[0]  # unless already known or pre-specified
v = [loc[0], loc[0]-1, loc[0]+1]
h = [loc[1], loc[1]-1, loc[1]+1]

output = []
for i in itertools.product(v, h):
    if not np.any(np.array(i) >= x.shape[0]) and not np.any(np.array(i) < 0): output.append(i)

print(output)
[(1, 1), (1, 0), (1, 2), (0, 1), (0, 0), (0, 2), (2, 1), (2, 0), (2, 2)]

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多