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

时间:2019-01-10 16:44:56

标签: 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+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]]

1 个答案:

答案 0 :(得分: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.