将CIFAR 1d数组从泡菜转换为图像(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])

这样我得到了一个数组列表,该数组仅对应一个类,比如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张图像,我认为这是由于整形

将CIFAR 1d数组从泡菜转换为图像(RGB)

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

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

给出以下图像作为输出

将CIFAR 1d数组从泡菜转换为图像(RGB)

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

beibeiji 回答:将CIFAR 1d数组从泡菜转换为图像(RGB)

问题本质上是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)) # get the first element from list

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

plt.imshow(imgView)
本文链接:https://www.f2er.com/3133268.html

大家都在问