我想标准化我的图像数据以进行深度学习的预处理

时间:2019-02-08 18:15:56

标签: python numpy

我将图像存储在gray_img_here,这是2d数组的python列表。 我想通过应用以下方法来标准化每张图像:X =(X-u)/ S其中X是像素值,U是图像的均值,S是该像素的偏差

def normalizeImages(self, gray_img_here):
    print "Normalizing the gray images..."
    print
    gray_img_numpy = np.array(gray_img_here)
    for i in range(len(gray_img_here)):
        print
        # print "mean of the {}th image", np.mean(gray_img_numpy[i])
        # print "std dev. of the {}th image", np.std(gray_img_numpy[i])
        # print
        gray_img_here[i] = float(gray_img_here[i] - np.mean(gray_img_numpy[i])) / float(np.std(gray_img_numpy[i], axis=0))

    return gray_img_here

但是我得到了错误: gray_img_here [i] = float(gray_img_here [i]-np.mean(gray_img_numpy [i]))/ float(np.std(gray_img_numpy [i],axis = 0))

TypeError:只有大小为1的数组可以转换为Python标量

gray_img_here看起来像这样

[array([[ 37,  39,  41, ..., 119, 113, 109],
   [ 38,  40,  41, ..., 119, 113, 109],
   [ 39,  41,  42, ..., 117, 112, 108],
   ...,
   [ 25,  25,  26, ..., 168, 180, 182],
   [ 25,  26,  26, ..., 179, 191, 189],
   [ 26,  26,  26, ..., 184, 196, 191]], dtype=uint8), array([[ 91,  97, 101, ...,  48,  49,  51],
   [ 89,  93,  98, ...,  44,  45,  45],
   [ 85,  88,  94, ...,  40,  41,  41],
   ...,
   [137,  90,  52, ...,  35,  36,  36],
   [163, 103,  68, ...,  35,  35,  35],
   [216, 148, 107, ...,  35,  35,  34]], dtype=uint8), array([[ 64,  75,  93, ...,  85,  83,  82],
   [ 83,  93,  98, ...,  85,  81,  80],
   [ 91,  98,  96, ...,  84,  80,  81],
   ...,

1 个答案:

答案 0 :(得分:0)

标准化3D矩阵要容易得多。像这样:

X=np.array(gray_img_here,dtype=float)
Xm=X.mean(axis=0,keepdims=True)
Xstd=X.std(axis=(1,2),keepdims=True)
X_standardised=list((X-Xm)/Xstd)

第一行生成3D浮点数组,因此您不必担心在每个步骤中进行投射。然后进行简单的标准化,并根据需要将其更改回列表。

注意: 无需将其保留为列表,您可以拥有3D numpy数组并以相同的方式寻址