首页 文章

如何根据图像结构决定np.reshape(图像,(形状))形状元组

提问于
浏览
0

我正在使用CIFAR 10数据集,并在从数据集中提取图像时遇到完全相同的问题

loading an image from cifar-10 dataset

此数据集中的图像具有以下结构 -

每个阵列都存储一个32x32彩色图像 . 前1024个条目包含红色通道值,下一个1024表示绿色,最后1024个表示蓝色 . 图像以行主顺序存储,因此数组的前32个条目是图像第一行的红色通道值 .

用于提取我正在做的图像(我以前做过并且工作过)

df_im = np.reshape(df ['data'],(df ['data'] . shape [0],32,32,3))

Not working Image

这种重塑不能按预期工作 .

但这有效 -

df_im = np.reshape(df ['data'],(df ['data'] . shape [0],3,32,32))

Working Image

Why the latter worked in in this case but not the former one. And how to decide the np.reshape "shape" tuple based on the flattened array structure.

1 回答

  • 0

    让我们用较小的“图像”重新创建数据:

    In [68]: R = np.arange(4)
    In [69]: G = np.arange(10,14)
    In [70]: B = np.arange(20,24)
    In [71]: rgb = np.hstack([R,G,B])
    In [72]: rgb
    Out[72]: array([ 0,  1,  2,  3, 10, 11, 12, 13, 20, 21, 22, 23])
    

    这看起来像你的一个图像,不是吗?前N个值为“红色”,下一个N为“绿色”等

    重塑为2d:

    In [73]: rgb.reshape(3,4)
    Out[73]: 
    array([[ 0,  1,  2,  3],
           [10, 11, 12, 13],
           [20, 21, 22, 23]])
    

    重塑为3d:

    In [74]: rgb.reshape(3,2,2)
    Out[74]: 
    array([[[ 0,  1],
            [ 2,  3]],
    
           [[10, 11],
            [12, 13]],
    
           [[20, 21],
            [22, 23]]])
    

    'row major'表示第一维是最外层的,并且变化最慢 . 最后一个维度是内部维度 .

    In [75]: rgb.reshape(2,2,3)
    Out[75]: 
    array([[[ 0,  1,  2],
            [ 3, 10, 11]],
    
           [[12, 13, 20],
            [21, 22, 23]]])
    

    reshape 保留数据元素的顺序 . 它只是改变了它们被观察,划分的方式,可以说是平面,行和列 .

相关问题