我有一个填充了 0 和 1 的 2D numpy 数组,我想对其进行转换,以便将与 1 相邻的每个值转换为 1(因此标题中的“污染”)。
例如:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 1 0 0 0
0 0 0 0 0 0
变成:
0 0 0 0 0 0
0 0 1 1 1 0
0 0 1 1 1 1
0 1 1 1 1 1
0 1 1 1 1 1
0 1 1 1 0 0
我可以通过循环所有值,找到 1,然后替换相邻值来实现此目的:
import numpy as np
ones = []
ar = np.array([[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,1,0,0],
[0,0,0,0,1,0],
[0,0,1,0,0,0],
[0,0,0,0,0,0]])
n_row, n_col = ar.shape
for i in range(n_row):
for j in range(n_col):
if ar[i][j] == 1:
ones.append((i, j))
for x,y in ones:
# Replace neighboring values
但这似乎有点矫枉过正(特别是因为我计划处理非常大的数组)。
有没有一种方法可以实现这一点,而不必循环遍历所有值?
最佳答案
这基本上就是dilation operation in Image-processing domain
。所以,你可以使用Scipy's binary dilation
-
from scipy.ndimage import binary_dilation
out = binary_dilation(arr, structure=np.ones((3,3))).astype(int)
示例运行 -
In [21]: arr
Out[21]:
array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
In [22]: binary_dilation(arr, structure=np.ones((3,3))).astype(int)
Out[22]:
array([[0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 0, 0]])
关于python - Numpy 数组值 "contamination",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37791468/