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

2020-07-08 07:46发布

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)

标签: python numpy
1条回答
家丑人穷心不美
2楼-- · 2020-07-08 08:15

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)
查看更多
登录 后发表回答