使用unpickle(python)从二进制文件中提取.jpg格式的图像

时间:2017-08-10 09:30:08

标签: python-2.7

我正在尝试从CIFAR-10数据二进制文件中提取图像,即data_batch_1.bin.jpg

但是在做unpickle的时候我遇到了错误。

我的代码是:

from PIL import Image
import numpy 

def unpickle(file):
    import pickle
    with open(file, 'rb') as fo:
        dict = pickle.load(fo)
    return dict


def save_as_image(img_flat):
    """
        Saves a data blob as an image file.
    """

    # consecutive 1024 entries store color channels of 32x32 image 
    img_R = img_flat[0:1024].reshape((32, 32))
    img_G = img_flat[1024:2048].reshape((32, 32))
    img_B = img_flat[2048:3072].reshape((32, 32))
    img = numpy.dstack((img_R, img_G, img_B))
    im = Image.fromarray(img)
    im.show()

abc = unpickle("/home/ubuntu/visit/cifar-10-batches-bin/data_batch_1.bin")
#print(abc)
data = abc["data"]
save_as_image(data[0])

我收到如下错误:

Traceback (most recent call last):
  File "load.py", line 24, in <module>
    abc = unpickle("/home/ubuntu/visit/cifar-10-batches-bin/data_batch_1.bin")
  File "load.py", line 7, in unpickle
    dict = pickle.load(fo)
  File "/usr/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/usr/lib/python2.7/pickle.py", line 858, in load
    dispatch[key](self)
KeyError: '\x06'

这个问题可能是什么原因?

0 个答案:

没有答案