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)
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)
For that specific function, few approaches could be listed.
Approach #1 : You can use
boolean indexing
for in-place setting -Approach #2 : You can also use
np.where
for a possibly more intuitive solution -With that
np.where
that has a syntax ofnp.where(mask,A,B)
, we are choosing between two equal shaped arraysA
andB
to produce a new array of the same shape asA
andB
. The selection is made based upon the elements inmask
, which is again of the same shape asA
andB
. Thus for everyTrue
element inmask
, we selectA
, otherwiseB
. Translating this to our case,A
would be(img*0.5).astype(int)
andB
isimg
.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 -