如何将像素向量转换为图像的numpy数组

2024-10-02 18:21:29 发布

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

例如,我从mat文件加载的背景Mnist为训练集提供50000x784

应该有50000个28x28图像

我用电脑重塑了整件事

    f_train = scio.loadmat('mnist_background_images/mnist_background_images_train.mat')
    f_test = scio.loadmat('mnist_background_images/mnist_background_images_test.mat')
    data_train = f_train['mnist_background_images_train']
    data_test = f_test['mnist_background_images_test'] #this gives 50,000x785 where last column is y
    x_train = data_train[:, :-1]
    x_test= data_test[:, :-1] #now it's 50,000x784
    x_train = np.reshape(x_train, newshape=(-1, 28, 28 )) #new shape 50,000x28x28
    x_test = np.reshape(x_test, newshape=(-1, 28, 28))

给出了正确的尺寸

然而,当我试图通过

img = x_train[2]
out = Image.fromarray(img, mode = 'L')
print(x_train.shape) 

给出(50000,784)

这张图片看起来一点也不像MNIST数据。像素混在一起,到处都是,好像所有的东西都被搅乱了一样。我是不是在什么地方犯了个愚蠢的错误


Tags: 文件testimgdatanptrainbackgroundimages
1条回答
网友
1楼 · 发布于 2024-10-02 18:21:29

Python代码中的逻辑是正确的。您的.mat文件似乎已损坏,或者至少不包含您认为应该包含的内容。(我个人对Python/Matlab数据交换一直感到头疼。)这不太可能,但你可以试试

data_train = data_train.T.reshape(50000, 785)

以防Matlab中的重塑操作不正确

如果加载original data,它将作为文件名后缀为.amat的文本文件提供

import numpy as np
data = np.loadtxt('mnist_background_images_test.amat', dtype=np.float32) # shape (50000, 785)
scale = 255 / data.max() 
data8 = np.array(data * scale, dtype=np.uint8) # 8-bit image data

y = data[:, -1].astype(int)
x = data8[:, :-1].reshape(-1, 28, 28)

import matplotlib.pyplot as plt
plt.close('all')
plt.imshow(x[2], cmap='Greys')
plt.show()

One image from the MNIST set

相关问题 更多 >