python - Numpy 数组值 "contamination"

标签 python arrays numpy python-3.5

我有一个填充了 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/

相关文章:

python - str 没有在 django 中添加对象

python - 迭代每个文件夹中的 2 个文件并比较它们

c - 确定每个元素在数组中出现的频率?

java - 将 2d double 数组转换为 2d int 数组

python - 从路径加载大量图像并将其转换为大小为 (n,224,224,3) 的数组

python - 在 numpy 中给定索引列表添加元素的最有效方法

python - Numpy 和 keras 张量大小调整困惑

python - 如何通过 "manage.py shell"使用交互式解释器重新加载 Django 模型模块?

python - 如何覆盖在 pytest 4 中调用原始的 pytest fixture

java - 按姓氏对对象数组进行排序java