如何获取矩阵中元素周围所有邻居的值?

How to get all the values of neighbours around an element in matrix?

我需要获取 python 中矩阵中某个元素周围所有邻居的值。假设我有一个如下所示的矩阵,

  matrix=[[1,2,3,4],
             [5,6,7,8],
             [9,10,11,12]]

对于第一个元素,即 matrix[0][0],邻居是 [2,5,6]

对于matrix[0][1],邻居是[1,3,5,6,7]

对于matrix[0][2],邻居是[2,4,6,7,8]

对于给定的元素,我需要获取这些值列表。

我可以通过在 i=0,j=0 时比较 i,j 值来做同样的事情,使用 switch 得到矩阵[0][1]、矩阵[1][0]、矩阵[1][1]案例等等。但是会变成冗长的代码。是否有任何内置功能或任何模块可以使上述任务更简单?

可以在矩阵中建立一个坐标和对应值的字典,方便查找:

matrix=[[1,2,3,4],
        [5,6,7,8],
        [9,10,11,12]]

def get_neighbors(a, b):
  d = {(i, c):matrix[i][c] for i in range(len(matrix)) for c in range(len(matrix[0]))}
  return filter(None, [d.get(i) for i in
    [(a+1, b+1), (a, b+1), (a+1, b), (a-1, b+1), (a-1, b), (a, b-1), (a+1, b-1)]])

cords = [(0, 0), (0, 1), (0, 2)]
results = [get_neighbors(*i) for i in cords]

输出:

[[6, 2, 5], [7, 3, 6, 1, 5], [8, 4, 7, 2, 6]]

如果不在意效率,就用scipy:

import scipy, scipy.ndimage

def nb_vals(matrix, indices):
    matrix = scipy.array(matrix)
    indices = tuple(scipy.transpose(scipy.atleast_2d(indices)))
    arr_shape = scipy.shape(matrix)
    dist = scipy.ones(arr_shape)
    dist[indices] = 0
    dist = scipy.ndimage.distance_transform_cdt(dist, metric='chessboard')
    nb_indices = scipy.transpose(scipy.nonzero(dist == 1))
    return [matrix[tuple(ind)] for ind in nb_indices]

例如

>>> matrix=[[1,2,3,4],
... [5,6,7,8],
... [9,10,11,12]]
>>>
>>> nb_vals(matrix, [1,1])
[1,2,3,5,7,9,10,11]

这是维度不可知论的(适用于任意数量的输入维度 "matrix")并处理任意数量的索引,您可能希望在这些索引周围找到邻居。

>>> arr_shape = (2,3,4,5)
>>> testMatrix = scipy.array(scipy.random.random(arr_shape)*10, dtype=int)
>>> print(testMatrix)
[[[[7 0 0 1 9]
   [9 5 8 5 8]
   [4 0 0 8 0]
   [1 9 1 3 2]]

  [[9 2 3 3 5]
   [2 3 3 7 9]
   [6 5 6 6 2]
   [9 1 1 0 0]]

  [[8 8 5 7 9]
   [9 0 7 7 6]
   [3 8 7 6 4]
   [8 7 5 5 9]]]

 [[[8 9 2 0 0]
   [8 3 5 5 2]
   [4 0 1 0 3]
   [1 0 9 1 3]]

  [[6 9 2 5 2]
   [2 7 5 5 3]
   [6 7 2 9 5]
   [4 2 7 3 1]]

  [[1 7 7 7 6]
   [5 1 4 1 0]
   [3 9 4 9 7]
   [7 7 6 6 7]]]]

>>> nb_vals(testMatrix, [1,2,2,3])
[3, 7, 9, 6, 6, 2, 1, 0, 0, 7, 7, 6, 7, 6, 4, 5, 5, 9, 5, 5, 3, 2, 9, 5, 7, 3, 1, 4, 1, 0, 4, 7, 6, 6, 7]

此解决方案在 image-like 二进制数组掩码上使用 chessboard-type 倒角变换,其中 1 等于掩码上的白色像素,0 等于到蒙版的黑色像素(背景)。倒角变换计算所有白色像素点到背景的棋盘距离;所有距离计算为 1 的像素位置都是邻居,并返回输入数组中这些位置的值。