【问题标题】:How to convert vectors of pixels to a numpy array of an image如何将像素向量转换为图像的numpy数组
【发布时间】:2020-06-20 17:31:33
【问题描述】:

例如,我从 mat 文件加载的 background-Mnist 为训练集提供了 50,000x784。

应该有 50,000 张 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 数据。像素混合在一起,到处都是,就像一切都被打乱了一样。我是不是在某个地方犯了一个愚蠢的错误?

【问题讨论】:

  • 你能显示从 .mat 文件加载数据的行吗?具体来说,你是用scipy.io.loadmat还是别的什么?
  • @Han-KwangNienhuys 是的,我做到了。 f_train = scio.loadmat('mnist_background_images/mnist_background_images_train.mat')这是代码
  • 您能否在重塑操作之前将其添加到问题以及print(x_train.shape) 的输出中。询问的原因是保存为“-v7.3”(HDF5)的 .mat 文件以转置形式存储数组,无论如何,matlab 代码可能无法将图像保存为您期望的形状。
  • @Han-KwangNienhuys 抱歉回复晚了,我已经添加了整个代码块。
  • print语句真的输出(50,000, 784)有两个逗号吗?

标签: python arrays matlab numpy python-imaging-library


【解决方案1】:

您的 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()

【讨论】:

  • 非常感谢!这有效:) 我从一个朋友那里得到了数据集,显然它来自一个 mat 文件。非常感谢您的帮助!
猜你喜欢
  • 2021-12-17
  • 2018-07-21
  • 1970-01-01
  • 2010-09-27
  • 2011-12-07
  • 2021-08-08
  • 2023-03-17
  • 2020-12-21
相关资源
最近更新 更多