Selection based on adjacent elements
Let’s say I have some numpy array myArr
. I know I can easily select myArr >
x to find the index of an element with a value higher than x
.
How do I find the element index of an adjacent element above x
? For one-dimensional arrays, the element neighboring some idx is (idx-1, idx+1).
For arrays of
dimension d
, I mean adjacent in any dimension. i.e. d=3
. myArr[2
, 2, 2]’s neighbors are [(1, 2, 2), (2, 1, 2), (2, 2, 1), (3, 2, 2), (2, 3, 2), (2, 2, 2, 3)].
For example, take
import numpy as np
test = np.arange(4**2).reshape((4,4))
Here, we can graphically see that the adjacent elements of 5
are [1, 4, 6, 9].
test
Out[10]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
I want to be able to choose based on adjacent elements. For example, I want all indexes with adjacent elements of >=9
. The following values apply in the example above: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
(4
really doesn’t count the adjacent no more than diagonal I defined.) )
My expected output would be a typical binary matrix:
neighboringIndicesLargerThan(myArr, 9)
array([[False, False, False, False],
[False, True, True, True],
[ True, True, True, True],
[ True, True, True, True]], dtype=bool)
It would be great if it worked on any size, but I need it to work at least 3.
Solution
Get an element mask greater than the threshold and simply use binary_dilation
Use the appropriate kernel to select the north + east + west + south, like this-
In [20]: from scipy.ndimage.morphology import binary_dilation
In [21]: mask = test >= 9
In [22]: kernel = np.array([[0,1,0],[1,0,1],[0,1,0]])
In [23]: binary_dilation(mask, kernel)
Out[23]:
array([[False, False, False, False],
[False, True, True, True],
[ True, True, True, True],
[ True, True, True, True]], dtype=bool)