将函数应用于蒙版的numpy数组 [英] Apply function to masked numpy array

查看:100
本文介绍了将函数应用于蒙版的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作为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.

方法1::您可以使用

Approach #1 : You can use boolean indexing for in-place setting -

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

方法2::您还可以使用

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,我们在两个相等形状的数组AB之间进行选择,以生成形状与AB相同的新数组.根据mask中的元素进行选择,该元素的形状又与AB相同.因此,对于mask中的每个True元素,我们选择A,否则选择B.将其转换为我们的情况,A将是(img*0.5).astype(int)Bimg.

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.

方法3::有一个内置的

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆