将 2D numpy 数组中的每个元素与其 8 个邻居进行比较的最有效方法

Most efficient way of comparing each element in a 2D numpy array to its 8 neighbours

因此,在二进制数组中,我试图找到 0 和 1 彼此相邻的点,并使用通过修改 0 值指示的这些交叉点重新绘制数组。只是想知道是否有比使用嵌套 for 循环更好的方法将 numpy 数组中的每个值与周围的 8 个值进行比较。

目前我有这个,与 4 周围相比只是为了这里的可读性

for x in range(1, rows - 1):
    for y in range(1, columns - 1):
        if f2[x, y] == 0:
            if f2[x-1, y] == 1 or f2[x+1, y] == 1 or f2[x, y-1] == 1 or f2[x, y+1] == 1:
                f2[x, y] = 2

编辑

例如

[[1, 1, 1, 1, 1, 1, 1],
 [1, 1, 0, 0, 0, 1, 1],
 [1, 1, 0, 0, 0, 1, 1],
 [1, 1, 0, 0, 0, 1, 1],
 [1, 1, 1, 1, 1, 1, 1]]

[[1, 1, 1, 1, 1, 1, 1],
 [1, 1, 2, 2, 2, 1, 1],
 [1, 1, 2, 0, 2, 1, 1],
 [1, 1, 2, 2, 2, 1, 1],
 [1, 1, 1, 1, 1, 1, 1]]

这个问题可以用二元形态学函数快速解决

import numpy as np
from scipy.ndimage.morphology import binary_dilation, generate_binary_structure

# Example array
f2 = np.zeros((5,5), dtype=float)
f2[2,2] = 1.

# This line determines the connectivity (all 8 neighbors or just 4)
struct_8_neighbors = generate_binary_structure(2, 2)

# Replace cell with maximum of neighbors (True if any neighbor != 0)
has_neighbor = binary_dilation(f2 != 0, structure=struct_8_neighbors)

# Was cell zero to begin with
was_zero = f2 == 0

# Update step
f2[has_neighbor & was_zero] = 2.