When dealing with an array of 0s and 1s, you may want to convert it to an boolean array and make use of the logical operators. And, slicing and indexing in numpy is very handy.
def expand_in_place(bool_matrix, expand_up=2, expand_down=2):
assert expand_up >= 0 and expand_down >= 0
# expands upward
for _ in range(expand_up):
bool_matrix[:-1] |= bool_matrix[1:].copy()
# expands downward
for _ in range(expand_down):
bool_matrix[1:] |= bool_matrix[:-1].copy()
Example usage:
matrix = np.array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]])
bool_matrix = matrix.astype(bool)
expand_in_place(bool_matrix)
print() # newline
print(bool_matrix.astype(int))
Output:
In [64]:
[[0 1 0 0]
[0 1 0 0]
[0 1 0 0]
[0 1 0 0]
[0 1 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 1 0]
[0 0 1 0]
[0 0 1 0]
[0 0 1 0]]
Explanation:
- The key is what happens when you call
bool_matrix[:-1] |= bool_matrix[1:] every time.
I add .copy() because bool_matrix[1:] |= bool_matrix[:-1] doesn't work as expected.
In [108]: small = np.array([False, False, True, False, False])
In [109]: small[1:] |= small[:-1]
In [110]: small
Out[110]:
array([False, False, True, True, True], dtype=bool)
- You can easily extend it to expand in four directions.
binary_dilationfunction with an appropriate array for the 'structure' kwarg might be a good option in that case.