简体   繁体   English

NumPy:填充数组中1周围的字段

[英]NumPy: fill fields surrounding a 1 in an array

Suppose I have a 4x4 matrix that looks like the following: 假设我有一个4x4矩阵,如下所示:

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

I want to write a function that takes all 4 surrounding fields of the one and turns them into a 1 as well. 我想写一个函数,它接受一个的所有4个周围的字段,并将它们变成1。

The above matrix would become: 上述矩阵将变为:

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

I know that this is possible using if-statements, but I really want to optimize my code. 我知道这可以使用if语句,但我真的想优化我的代码。

The matrix only contains 0's and 1's. 矩阵只包含0和1。 If the 1 is at the edge of the matrix, the 1's should not wrap around, ie if the most left field is a 1, the most right field still stays at 0. Also, I am using Python 3.5 如果1位于矩阵的边缘,则1不应该环绕,即如果最左边的字段是1,则最右边的字段仍然保持为0.此外,我使用的是Python 3.5

Is there a more mathematical or concise way to do this? 有没有更多数学或简洁的方法来做到这一点?

This looks like binary dilation. 这看起来像二元扩张。 There's a function available in SciPy that implements this efficiently: SciPy中有一个可以有效实现这一功能的功能:

>>> from scipy.ndimage import binary_dilation
>>> x
array([[0, 0, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])

>>> binary_dilation(x).astype(int)
array([[0, 0, 1, 0],
       [0, 1, 1, 1],
       [0, 0, 1, 0],
       [0, 0, 0, 0]])

1s at the edges are handled as you've specified they should be (ie no wrapping). 边缘处的1s处理,因为你已经指定它们应该是(即没有包装)。

See the documentation for further options and arguments. 有关更多选项和参数,请参阅文档

FWIW, here's a way to do it just using Numpy. FWIW,这是一种只使用Numpy的方法。 We pad the original data with rows & columns of zeros, and then bitwise-OR offset copies of the padded array together. 我们用零行和列填充原始数据,然后将填充数组的按位OR偏移副本放在一起。

import numpy as np

def fill(data):
    rows, cols = data.shape
    padded = np.pad(data, 1, 'constant', constant_values=0)
    result = np.copy(data)
    for r, c in ((0, 1), (1, 0), (1, 2), (2, 1)):
        result |= padded[r:r+rows, c:c+cols]
    return result

data = np.asarray(
    [
        [0, 0, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
    ], dtype='uint8')
print(data, '\n')

result = fill(data)
print(result)

output 产量

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM