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

Python 将2D numpy数组中的每个元素与其8个相邻元素进行比较的最有效方法,python,numpy,binary,neighbours,Python,Numpy,Binary,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

因此,在一个二进制数组中,我试图找到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]]


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

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.

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

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.

请共享输入和预期输出我想我在这里看到了一个二维卷积问题,但a会有帮助。谢谢,我现在添加了一个示例请共享输入和预期输出我想我在这里看到了一个二维卷积问题,但a会有帮助。谢谢,我现在添加了一个示例