4

我想在我的 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]] 

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

[[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]]

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

4

3 回答 3

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)]
于 2018-10-22T00:20:46.747 回答
1

这里没有感兴趣的算法。如果你还不知道1 在哪里,首先你必须找到它,你不能比搜索每个元素做得更好。(您可以numpy通过在 C 速度下使用argmax;将扁平索引分隔为行和列来获得恒定因子加速divmod。)此后,您所做的就是将 ±1(或 0)添加到坐标,除非它需要你在数组范围之外。您永远不会构建坐标只是为了以后丢弃它们。

于 2018-10-21T23:27:14.067 回答
0

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

设置数据:

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-10-22T00:26:05.390 回答