简体   繁体   English

numpy 数组的平均像素减法

[英]mean pixel subtraction for numpy array

I have a numpy array of grayscale images.我有一个 numpy 灰度图像数组。 The shape of the array is数组的形状是

imgs.shape
(100, 1, 300, 300)

which represents 100 images of grayscale (1 channel) and size 300x300.它表示 100 张灰度图像(1 个通道),大小为 300x300。

I want to do mean pixel subtraction for this array.我想为这个数组做平均像素减法。 That means I want to substract the mean pixel from all images.这意味着我想从所有图像中减去平均像素。

I want the mean over all images.我想要所有图像的平均值。

For a single image that would be something like this:对于像这样的单个图像:

X_mean = X.mean(0)
X -= X_mean

How can I do that for my array?我怎样才能为我的阵列做到这一点?

If its mean of one image at a time, we could compute the mean across the last two axes keeping the dimensions (that eases up code for subtraction later on) and simply subtract from original input, like so -如果它一次是一张图像的平均值,我们可以计算最后两个轴的平均值,保持维度(这简化了以后减法的代码),然后简单地从原始输入中减去,就像这样 -

imgs -= imgs.mean(axis=(-2,-1),keepdims=1)

If its mean across all images, include the first axis too -如果它在所有图像中的平均值,也包括第一个轴 -

imgs -= imgs.mean(axis=(0,-2,-1),keepdims=1)

Note that the mean values would be by default as float values.请注意,默认情况下mean将作为浮点值。 So, if imgs is not of float type, we need to make a copy of imgs as float dtype and then subtract from it, or convert the mean values to be of same dtype as imgs and then subtract.因此,如果imgs不是 float 类型,我们需要将imgs复制为 float imgs然后从中减去,或者将mean转换为与imgs相同的imgs然后减去。

Sample run -样品运行 -

In [188]: imgs = np.random.randint(0, 255,(10,1,30,30))

In [189]: out = imgs - imgs.mean(axis=(0,-2,-1),keepdims=1)

In [190]: out.shape
Out[190]: (10, 1, 30, 30)

In [191]: out.dtype
Out[191]: dtype('float64')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM