The Python Oracle

Select based on neighbouring elements

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop

--

Chapters
00:00 Question
01:59 Accepted answer (Score 3)
02:27 Thank you

--

Full question
https://stackoverflow.com/questions/4805...

Accepted answer links:
[binary_dilation]: https://docs.scipy.org/doc/scipy-0.14.0/...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy

#avk47



ACCEPTED ANSWER

Score 3


Get mask of elements greater than the threshold and simply use binary_dilation with an appropriate kernel to select north+east+west+south ones, like so -

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)