Search code examples
python-2.7numpymask

Apply function to masked numpy array


I've got an image as numpy array and a mask for image.

from scipy.misc import face

img = face(gray=True)
mask = img > 250

How can I apply function to all masked elements?

def foo(x):
    return int(x*0.5) 

Solution

  • For that specific function, few approaches could be listed.

    Approach #1 : You can use boolean indexing for in-place setting -

    img[mask] = (img[mask]*0.5).astype(int)
    

    Approach #2 : You can also use np.where for a possibly more intuitive solution -

    img_out = np.where(mask,(img*0.5).astype(int),img)
    

    With that np.where that has a syntax of np.where(mask,A,B), we are choosing between two equal shaped arrays A and B to produce a new array of the same shape as A and B. The selection is made based upon the elements in mask, which is again of the same shape as A and B. Thus for every True element in mask, we select A, otherwise B. Translating this to our case, A would be (img*0.5).astype(int) and B is img.

    Approach #3 : There's a built-in np.putmask that seems to be the closest for this exact task and could be used to do in-place setting, like so -

    np.putmask(img, mask, (img*0.5).astype('uint8'))