I’m performing a image analysis and generated seeds in the form of a boolean array
:
JavaScript
10
1
import numpy as np
2
3
# Example output array
4
a = np.array([[False, False, False], [False, True, False], [False, False, False]])
5
6
>>> a
7
array([[False, False, False],
8
[False, True, False],
9
[False, False, False]])
10
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:
JavaScript
5
1
>>> a
2
array([[False, True, False],
3
[True, True, True],
4
[False, True, False]])
5
Is there any function
or simple way of solving my ‘radial expansion’ problem?
Thanks in advance, BBQuercus
Advertisement
Answer
Solution with scipy.signal.convolve2d:
JavaScript
34
1
import numpy as np
2
from scipy.signal import convolve2d
3
4
5
# Example input
6
# [[False False False False False]
7
# [False False True True False]
8
# [False False False False False]
9
# [False False False False False]
10
# [False False False False True]]
11
in_array = np.zeros((5, 5), dtype=bool)
12
in_array[1,2] = True
13
in_array[1,3] = True
14
in_array[4,4] = True
15
16
# Kernel: here you should define how much the True "dilates"
17
18
kernel = np.asarray([[False, True, False],
19
[True, True, True],
20
[False, True, False]])
21
22
# Convolution happens here
23
# Convolution is not possible for bool values though, so we convert to int and
24
# back. That works because bool(N) == True if N != 0.
25
result = convolve2d(in_array.astype(int), kernel.astype(int), mode='same').astype(bool)
26
print(result)
27
28
# Result:
29
# [[False False True True False]
30
# [False True True True True]
31
# [False False True True False]
32
# [False False False False True]
33
# [False False False True True]]
34