将函数应用于屏蔽的 numpy 数组

Apply function to masked numpy array

我有一个图像作为 numpy 数组和一个图像掩码。

from scipy.misc import face

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

如何将函数应用于所有屏蔽元素?

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

对于该特定功能,可以列出的方法很少。

方法 #1: 您可以使用 boolean indexing 进行就地设置 -

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

方法 #2: 您还可以使用 np.where 来获得可能更直观的解决方案 -

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

有了语法为 np.where(mask,A,B)np.where,我们在两个相同形状的数组 AB 之间进行选择,以生成相同的新数组形状为 AB。 selection 是基于 mask 中的元素制成的,其形状与 AB 相同。因此,对于 mask 中的每个 True 元素,我们 select A,否则 B。将其转化为我们的案例,A 将是 (img*0.5).astype(int)B 将是 img.

方法 #3 : 有一个内置的 np.putmask 似乎最接近这个确切的任务,可用于进行就地设置,像这样 -

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