将 CIFAR 一维数组从 pickle 转换为图像 (RGB)

Convert a CIFAR 1d array from pickle to an image (RGB)

编辑:classes 的分离。原始 pickle 文件提供了一个包含标签、数据(数组)和文件名的字典。我只是根据 class 标签过滤数组并附加所有数组以形成一个列表,然后将这个列表一起腌制。

class_index= 9 #gives the corresponding class label in the dataset
images = [] #empty list 
for i in range(len(labels)):
    if labels[i]==class_index:
        images.append(data[i])

有了这个,我得到了一个数组列表,只对应一个 class say dog。 然后我将它们转储到泡菜文件中

with open('name.pkl', 'wb') as f:
    pickle.dump(images0, f)

当我加载 pickle 文件时,它会输出数组,每个数组的形状都是 (3072,)。

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

#Load the pickle
images = np.load('name.pkl',allow_pickle=True) 

我需要将它们作为 RGB 图像 (32,32,3) 获取。这些是尝试过的方法

image = images[0]
img = np.reshape(image,(32,32,3))
im = Image.fromarray(img)

这给出了一个非常扭曲的图像,看起来像同一项目的 9 个图像,我认为这是由于重塑造成的

有没有办法避免这种情况? 我也试过

image = image.reshape(-1,1)
pict = Image.fromarray(image,'L')
plt.imshow(pict)

输出以下图像

有人可以帮帮我吗?也欢迎其他方法

问题本质上是 reshape 命令。由于在深度学习中,输入图像被定义为 [batchsize, channels, height, width],因此要以正确的形式查看图像,您应该将其大小调整为 (3,32,32).

的形状

这是获得所需输出的最少代码:

import pickle
import numpy as np
import matplotlib.pyplot as plt

with open('pickleFile.pkl', 'rb') as f:
    imgList= pickle.load(f)

img = np.reshape(imgList[0],(3,32,32)) # get the first element from list

# inorder to view in imshow we need image of type (height,width, channel) rather than (channel, height,width)
imgView=np.transpose(img, (1,2,0))

plt.imshow(imgView)