重塑图像数组

2024-06-14 05:20:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有60000张火车图像作为一个形状矩阵(282860000)带来。这是一个裸体.ndarray。我想把它转换成一个一维图像数组,这意味着每个图像都表示为一行/一组数字,我想要60000个数组。换句话说,我想从(28,28,60000)到(600028*28)。在python中,它是:

images_features = []
for image in images:
    imageLine = []
    for y in range(len(image)):
        for x in range(len(image[0])):
            imageLine.append(image[y][x])
    images_features.append(imageLine)

我该怎么做?我怀疑我需要使用整形,但我不知道我到底能怎么做。

这就是我获取图像的方式:

data = scipy.io.loadmat('train.mat')


images = data["train_images"]

所以“图像”就是我说的数组。

有人建议我:

“您可能需要更改轴或合并轴,以获得所需的功能。我也建议绘制它们,以防图像横向结束。一定要用好斧头,以免再出现问题。”

我不知道这里指的是什么“轴”,也不知道如何考虑上面所说的。

有人能解释一下我需要做什么和为什么吗?(它的作用)


Tags: in图像imagefordatalenrangetrain
3条回答

你可以重塑train_images并通过绘制图像来验证它

重塑:

train_features_images = train_images.reshape(train_images.shape[0],28,28) 

绘制图像:

import matplotlib.pyplot as plt
def show_images(features_images,labels,start, howmany):
    for i in range(start, start+howmany):
        plt.figure(i)
        plt.imshow(features_images[i], cmap=plt.get_cmap('gray'))
        plt.title(labels[i])
    plt.show()
show_images(train_features_images, labels, 1, 10)

因为这是通过loadmat来的,所以(28,28,60000)的形状是有意义的-MATLAB从最后一个索引开始迭代。

images.transpose()  # or images.T

重新排序轴,结果是(60000,28,28)。最后两个维度可以与整形相结合

images.T.reshape(60000,28*28)
images.T.reshape(60000,-1)   # short hand

你需要将28x28图像转置

images.transpose([2,0,1])  # instead of the default [2,1,0]

.T与MATLAB'(或.')相同。

images也可以是order='F'


octave:38> images=reshape(1:30,2,3,5);
octave:39> save test.mat -v7 images
octave:40> images
images =

ans(:,:,1) =

   1   3   5
   2   4   6

ans(:,:,2) =

    7    9   11
    8   10   12
....

我选择的测试尺寸要小,并且便于区分不同的轴。

在Ipython会话中:

In [15]: data=io.loadmat('test.mat')

In [16]: data
Out[16]: 
{'__globals__': [],
 '__header__': 'MATLAB 5.0 MAT-file, written by Octave 3.8.2, 2016-02-10 05:19:18 UTC',
 '__version__': '1.0',
 'images': array([[[  1.,   7.,  13.,  19.,  25.],
        [  3.,   9.,  15.,  21.,  27.],
        [  5.,  11.,  17.,  23.,  29.]],

       [[  2.,   8.,  14.,  20.,  26.],
        [  4.,  10.,  16.,  22.,  28.],
        [  6.,  12.,  18.,  24.,  30.]]])}

In [18]: data['images'].T
Out[18]: 
array([[[  1.,   2.],
        [  3.,   4.],
        [  5.,   6.]],

       [[  7.,   8.],
        [  9.,  10.],
        [ 11.,  12.]],
....
In [19]: data['images'].transpose([2,0,1])
Out[19]: 
array([[[  1.,   3.,   5.],
        [  2.,   4.,   6.]],

       [[  7.,   9.,  11.],
        [  8.,  10.,  12.]],
 ....
In [22]: data['images'].transpose([2,1,0]).reshape(5,-1)
Out[22]: 
array([[  1.,   2.,   3.,   4.,   5.,   6.],
       [  7.,   8.,   9.,  10.,  11.,  12.],
 ...

我认为你只需要使用整形:

>>> images = np.ndarray([60000, 28, 28])
>>> images.shape
(60000, 28, 28)
>>> images_rs = images.reshape([60000, 28*28])
>>> images_rs.shape
(60000, 784)

相关问题 更多 >