Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Boundaries of an 'numpy.array'?

Tags:

python

numpy

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)
like image 562
FooBar Avatar asked Feb 04 '23 02:02

FooBar


1 Answers

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)
like image 140
jakevdp Avatar answered Feb 23 '23 18:02

jakevdp