因此,给定一个由 1 和 0 组成的 2d numpy 数组,我想找到值为 1 和 的每个索引,其中顶部、左侧、右侧或底部由一个零。例如在这个数组中
0 0 0 0 0
0 0 1 0 0
0 1 1 1 0
0 0 1 0 0
0 0 0 0 0
我只需要(1,2)、(2,1)、(2,3) 和(3,2) 的坐标,但不需要(2,2) 的坐标。
我已经创建了可以工作并创建两个坐标列表的代码,类似于 numpy 非零方法,但是我不认为它非常“Pythonic”,我希望有一种更好、更有效的方法来解决这个问题。 (*注意这仅适用于用零填充的数组)
from numpy import nonzero
...
array= ... # A numpy array consistent of zeros and ones
non_zeros_pairs=nonzero(array)
coordinate_pairs=[[],[]]
for x, y in zip(temp[0],temp[1]):
if array[x][y+1]==0 or array[x][y-1]==0 or array[x+1][y]==0 or array[x-1][y]==0:
coordinate_pairs[0].append(x)
coordinate_pairs[1].append(y)
...
如果 numpy 中存在可以为我处理这个问题的方法,那就太棒了。如果这个问题之前已经在 stackoverflow 上被问过/回答过,我会很乐意删除这个问题,我只是很难找到任何东西。谢谢。
最佳答案
设置
import scipy.signal
import numpy as np
a = np.array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]])
创建一个与每个值的四个方向相匹配的窗口,然后进行卷积
。然后,您可以检查元素是否为 1
,以及它们的卷积是否小于 4
,因为值 ==4
意味着该值被 1s
window = np.array([[0, 1, 0],
[1, 0, 1],
[0, 1, 0]])
m = scipy.signal.convolve2d(a, window, mode='same', fillvalue=1)
v = np.where(a & (m < 4))
list(zip(*v))
[(1, 2), (2, 1), (2, 3), (3, 2)]
关于python - 在 numpy 数组中查找与特定条件匹配的所有坐标对的最 Pythonic 方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56675009/