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) 回答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