【问题标题】:Convert a CIFAR 1d array from pickle to an image (RGB)将 CIFAR 1d 数组从 pickle 转换为图像 (RGB)
【发布时间】:2019-11-09 10:27:02
【问题描述】:

编辑:类分离。原始的 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)

当我加载一个 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)

它给出以下图像作为输出

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

【问题讨论】:

  • 你从哪里得到原始的pickle?你做了吗?如何?看起来您的数组的颜色尺寸与空间尺寸混合在一起。
  • 这是 CIFAR-10 泡菜。但我将其修改为仅包含一类数据,这是我的要求
  • 你的修改可能是混淆了,你能编辑你的问题来显示你做了什么吗?
  • 当然我也添加了。但是我看不到附加两个不同的数组列表会如何影响空间维度,因为我保持数组相同。我在获取图像时一个一个地访问每个数组

标签: python image numpy python-imaging-library pickle


【解决方案1】:

问题本质上是重塑命令。由于在深度学习中输入图像被定义为[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)

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 2016-12-23
    • 2011-12-07
    相关资源
    最近更新 更多