If I have an d
dimensional np.array
, how can I get the indicies of the boundary?
For example, in 2d,
test = np.arange(16).reshape((4, 4))
test
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Now I would like to get the boundaries
array([[ True, True, True, True],
[ True, False, False, True],
[ True, False, False, True],
[ True, True, True, True]])
Great if efficient and works for arbitrary number of dimensions, but it has to work at least 3. The array is not a necessarily a hypercube, but potentially a hyperrectangle: the number of grid points in all dimension are not necessarily the same, unlike in the example.
For an array of shape (4, 5, 6)
, the expected output is
array([[[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True]],
[[ True, True, True, True, True, True],
[ True, False, False, False, False, True],
[ True, False, False, False, False, True],
[ True, False, False, False, False, True],
[ True, True, True, True, True, True]],
[[ True, True, True, True, True, True],
[ True, False, False, False, False, True],
[ True, False, False, False, False, True],
[ True, False, False, False, False, True],
[ True, True, True, True, True, True]],
[[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True]]], dtype=bool)
You could do this by constructing a tuple of slices, e.g.
import numpy as np
def edge_mask(x):
mask = np.ones(x.shape, dtype=bool)
mask[x.ndim * (slice(1, -1),)] = False
return mask
x = np.random.rand(4, 5)
edge_mask(x)
# array([[ True, True, True, True, True],
# [ True, False, False, False, True],
# [ True, False, False, False, True],
# [ True, True, True, True, True]], dtype=bool)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With