简体   繁体   English

查询numpy二维数组中一个元素的四个邻居的值

[英]Query the value of the four neighbors of an element in a numpy 2D array

I have a 2D array of 5*5 like this:我有一个 5*5 的二维数组,如下所示:

>>> np.random.seed(100)
>>> a = np.random.randint(0,100, (5,5))
>>> a
array([[ 8, 24, 67, 87, 79],
       [48, 10, 94, 52, 98],
       [53, 66, 98, 14, 34],
       [24, 15, 60, 58, 16],
       [ 9, 93, 86,  2, 27]])

if I have an initial position, is there any way to quickly and easily get the values of its four neighbors around it?如果我有一个初始的 position,有什么方法可以快速轻松地获取它周围四个邻居的值? The method I'm using now is a bit cumbersome:我现在使用的方法有点麻烦:

Suppose the current position is [x, y] (if x=2, y=3 then the value in the array is 14,),then the position above it is [x-1, y], the bottom is [x+1, y], the left side is [y-1, x], and the right side is [y+1, x].假设当前 position 为 [x, y](如果 x=2, y=3 则数组中的值为 14,),则其上方的 position 为 [x-1, y],底部为 [x+ 1, y],左边是[y-1, x],右边是[y+1, x]。 I use the following four lines of code to get the values of neighbors.我使用以下四行代码来获取邻居的值。

curr_val = a[2,3]
up_val = a[2+1, 3]
bott_val = a[2-1, 3]
left_val = a[2, 3+1]
right_val = a[2, 3-1]

So my question is is there a more convenient function in numpy that can do this and even query the values of four neighbors at once?所以我的问题是 numpy 中是否有更方便的 function 可以做到这一点,甚至可以一次查询四个邻居的值?

This is not the shortest method, but a flexible way could be to use a mask and a convolution to build this mask.这不是最短的方法,但一种灵活的方法是使用掩码和卷积来构建此掩码。

The advantage is that you can use any mask easily, just change the kernel.优点是您可以轻松使用任何面罩,只需更换 kernel。

from scipy.signal import convolve2d

kernel = [[0,1,0],  # define points to pick around the target
          [1,0,1],
          [0,1,0]]
mask = np.zeros_like(a, dtype=bool) # build empty mask
mask[x,y] = True                    # set target(s)

# boolean indexing
a[convolve2d(mask, kernel, mode='same').astype(bool)]

output: array([52, 98, 34, 58]) output: array([52, 98, 34, 58])

The fastest way is this one taking usec to compute.最快的方法是使用 usec 来计算。 Some times shortest is not the best.有时最短的并不是最好的。 This one is very simple to understand and has no package dependencies.这个很容易理解,没有 package 依赖。

This also works for edge-cases.这也适用于边缘情况。

def neighbors(matrix: np.ndarray, x: int, y: int):
    x_len, y_len = matrix.shape
    nbr = []
    if x != 0:
        nbr.append(matrix[x-1][y])
    if y != 0:
        nbr.append(matrix[x][y-1])
    if x != x_len:
        nbr.append(matrix[x+1][y])
    if y != y_len:
        nbr.append(matrix[x][y+1])
    return nbr

You can also use:您还可以使用:

mask = np.array([[0, 1, 0],
                 [1, 0, 1],
                 [0, 1, 0]]).astype(bool)
a[i-1:i+2, j-1:j+2][mask]

output: output:

array([53, 93, 94, 86])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM