Numpy-标准化RGB图像数据集

cmp*_*x96 3 python numpy image machine-learning data-processing

我的数据集是一个尺寸为(N,W,H,C)的Numpy数组,其中N是图像数,H和W分别是高度和宽度,C是通道数。

我知道那里有很多工具,但是我只想用Numpy标准化图像。

我的计划是计算三个通道中每个通道的整个数据集的平均值和标准偏差,然后减去平均值并除以标准偏差。

假设我们在数据集中有两个图像,并且这两个图像的第一个通道如下所示:

x=array([[[3., 4.],
          [5., 6.]],

          [[1., 2.],
          [3., 4.]]])
Run Code Online (Sandbox Code Playgroud)

计算均值:

numpy.mean(x[:,:,:,0])
= 3.5
Run Code Online (Sandbox Code Playgroud)

计算std:

numpy.std(x[:,:,:,0])
= 1.5
Run Code Online (Sandbox Code Playgroud)

规范化第一个通道:

x[:,:,:,0] = (x[:,:,:,0] - 3.5) / 1.5
Run Code Online (Sandbox Code Playgroud)

它是否正确?

谢谢!

cwi*_*olf 5

看起来不错,但是NumPy在某些方面可以做得更好。我假设您要分别标准化每个通道。

首先,请注意x具有方法mean,因此我们可以编写x[..., 0].mean()而不是np.mean(x[:, :, :, 0])。同样,该mean方法采用关键字arguments axis,我们可以按如下方式使用它:

means = x.mean(axis=(0, 1, 2)) # Take the mean over the N,H,W axes
means.shape # => will evaluate to (C,)
Run Code Online (Sandbox Code Playgroud)

然后我们可以像这样从整个数据集中减去均值:

centered = x - x.mean(axis=(0,1,2), keepdims=True)
Run Code Online (Sandbox Code Playgroud)

请注意,我们必须在keepdims这里使用。

还有一个x.std以相同的方式工作,因此我们可以在1行中完成整个归一化:

z = (x - x.mean(axis=(0,1,2), keepdims=True)) / x.std(axis=(0,1,2), keepdims=True)
Run Code Online (Sandbox Code Playgroud)

Check out the docs for numpy.ndarray.mean and np.ndarray.std for more info. The np.ndarray.method methods are what you hit when you call x.method instead of using np.method(x) instead.


Edit: I have since learned that, of course, there is a scipy.stats.zscore. I'm not sure if this is a more readable way to take zscores along each channel, but some might prefer it:

z = zscore(x.reshape(-1, 3)).reshape(x.shape)
Run Code Online (Sandbox Code Playgroud)

The scipy function operates only over a single axis, so we have to reshape into an NHW x C matrix first and then reshape back.

  • 很好的答案,仅建议链接到Numpy的文档,以便感兴趣的各方可以阅读文档中有关参数的内容。 (2认同)