I’m performing a image analysis and generated seeds in the form of a boolean array :
import numpy as np
# Example output array
a = np.array([[False, False, False], [False, True, False], [False, False, False]])
>>> a
array([[False, False, False],
[False, True, False],
[False, False, False]])
As I want to do a subsequent analysis on the area surrounding the True value, I want to expand it (by a certain number, say pixels). This would result in the following:
>>> a
array([[False, True, False],
[True, True, True],
[False, True, False]])
Is there any function or simple way of solving my ‘radial expansion’ problem?
Thanks in advance, BBQuercus
Advertisement
Answer
Solution with scipy.signal.convolve2d:
import numpy as np
from scipy.signal import convolve2d
# Example input
# [[False False False False False]
# [False False True True False]
# [False False False False False]
# [False False False False False]
# [False False False False True]]
in_array = np.zeros((5, 5), dtype=bool)
in_array[1,2] = True
in_array[1,3] = True
in_array[4,4] = True
# Kernel: here you should define how much the True "dilates"
kernel = np.asarray([[False, True, False],
[True, True, True],
[False, True, False]])
# Convolution happens here
# Convolution is not possible for bool values though, so we convert to int and
# back. That works because bool(N) == True if N != 0.
result = convolve2d(in_array.astype(int), kernel.astype(int), mode='same').astype(bool)
print(result)
# Result:
# [[False False True True False]
# [False True True True True]
# [False False True True False]
# [False False False False True]
# [False False False True True]]