Search code examples
pythonnumpymask

Rectangular mask in an array


I would like to apply a mask all around the edges of an array, as example in a 3x3 array :

0 0 0
0 1 0
0 0 0

In stack i found this command, but i can t apply a second condition to get my specific array...

import numpy as np
np.logical_and.outer(np.arange(3) >= 2, np.arange(3) >= 2)

I get that :

0 0 0
0 0 0 
0 0 1

Solution

  • You could always construct a mask to deselect the first and last rows/columns like this:

    >>> mask = np.ones((3, 3), dtype=bool)
    >>> mask 
    array([[True, True, True],
           [True, True, True],
           [True, True, True]], dtype=bool)
    
    >>> mask[0], mask[-1], mask[:,0], mask[:,-1] = False, False, False, False
    >>> mask
    array([[ False,  False,  False],
           [ False,  True,   False],
           [ False,  False,  False]], dtype=bool)