将函数应用于蒙版的numpy数组 [英] Apply function to masked numpy array
问题描述
我有一个作为numpy数组的图像和一个图像蒙版.
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 -
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)
使用语法为np.where(mask,A,B)
的np.where
,我们在两个相等形状的数组A
和B
之间进行选择,以生成形状与A
和B
相同的新数组.根据mask
中的元素进行选择,该元素的形状又与A
和B
相同.因此,对于mask
中的每个True
元素,我们选择A
,否则选择B
.将其转换为我们的情况,A
将是(img*0.5).astype(int)
,B
是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'))
这篇关于将函数应用于蒙版的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!