Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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'))

Post a Comment for "Apply Function To Masked Numpy Array"