首页 > 解决方案 > 将 CIFAR 1d 数组从 pickle 转换为图像 (RGB)

问题描述

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

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])

有了这个,我得到了一个数组列表,对应于一个类说狗。然后我只是将它们转储到泡菜文件中

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

当我加载一个泡菜文件时,它会给我一个数组的输出,每个数组都是成形的(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)

它给出了以下图像作为输出 空图像

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

标签: pythonimagenumpypython-imaging-librarypickle

解决方案


问题本质上是重塑命令。由于在深度学习中,输入图像被定义为[batchsize, channels, height, width]以正确的形式查看图像,您应该将其调整为 shape (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)

推荐阅读