将 Numpy 图像数组居中

Centering a Numpy array of images

我有一些我想要居中的 numpy 图像数组(减去均值并除以标准差)。我可以简单地这样做吗?

# x is a np array
img_mean = x.mean(axis=0)
img_std = np.std(x)
x = (x - img_mean) / img_std

我不认为这是你想要做的。
假设我们有一个这样的数组:

In [2]: x = np.arange(25).reshape((5, 5))

In [3]: x
Out[3]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

x.mean(axis=0) 计算每列(轴 0)的平均值:

In [4]: x.mean(axis=0)
Out[4]: array([ 10.,  11.,  12.,  13.,  14.])

从我们原来的 x 数组中减去,每个值都减去其列的平均值:

In [5]: x - x.mean(axis=0)
Out[5]: 
array([[-10., -10., -10., -10., -10.],
       [ -5.,  -5.,  -5.,  -5.,  -5.],
       [  0.,   0.,   0.,   0.,   0.],
       [  5.,   5.,   5.,   5.,   5.],
       [ 10.,  10.,  10.,  10.,  10.]])

如果我们不为 x.mean 指定轴,则将采用整个数组:

In [6]: x.mean(axis=None)
Out[6]: 12.0

这就是您一直在使用 x.std() 所做的事情,因为对于 np.std and np.mean 两者,默认轴都是 None.
这可能是您想要的:

In [7]: x - x.mean()
Out[7]: 
array([[-12., -11., -10.,  -9.,  -8.],
       [ -7.,  -6.,  -5.,  -4.,  -3.],
       [ -2.,  -1.,   0.,   1.,   2.],
       [  3.,   4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.,  12.]])

In [8]: (x - x.mean()) / x.std()
Out[8]: 
array([[-1.6641005, -1.5254255, -1.3867504, -1.2480754, -1.1094003],
       [-0.9707253, -0.8320502, -0.6933752, -0.5547002, -0.4160251],
       [-0.2773501, -0.1386750,  0.       ,  0.1386750,  0.2773501],
       [ 0.4160251,  0.5547002,  0.6933752,  0.8320502,  0.9707253],
       [ 1.1094003,  1.2480754,  1.3867504,  1.5254255,  1.6641005]])