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

Ssu*_*mar 5 python list matrix nearest-neighbor python-3.x

我需要在python中获取矩阵中元素周围所有邻居的值。假设我有一个像下面这样的矩阵,

  matrix=[[1,2,3,4],
             [5,6,7,8],
             [9,10,11,12]]
Run Code Online (Sandbox Code Playgroud)

对于第一个元素,即 ,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 值来做同样的事情,得到 matrix[0][1], matrix[1][0], matrix[1][1] 使用 switch case 等等。但它会变成冗长的代码。是否有任何内置功能或任何模块可以使上述任务更简单?

dro*_*oze 3

如果您不关心效率,请使用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]
Run Code Online (Sandbox Code Playgroud)

例如

>>> 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]
Run Code Online (Sandbox Code Playgroud)

这是与维度无关的(适用于输入“矩阵”的任意数量的维度)并处理您可能希望找到周围邻居的任意数量的索引。

>>> 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]
Run Code Online (Sandbox Code Playgroud)

该解决方案在类似图像的二进制数组掩模上使用棋盘型倒角变换,其中1等于掩模上的白色像素,并且0等于掩模上的黑色像素(背景)。倒角变换计算所有白色像素到背景的棋盘距离;所有距离计算为 1 的像素位置都是邻居,并且返回输入数组上这些位置的值。

  • @MadPhysicist你可能想详细说明你的意思。对于用户想要为邻居选择任意维数和任意数量元素的数组,我相信这样做会更干净。截至目前,我完全看不出您发表评论的意义。 (2认同)