Abinav R
Abinav R

Reputation: 375

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

EDIT: separation of classes. The original pickle file gives a dictionary with labels, data (array) and filenames. I just filtered the arrays according to class labels and appended all arrays to form a list and then pickled this list together.

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 this I get a list of arrays corresponding to just one class say dog. then I just dump them in a pickle file

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

When I load a pickle file it gives me an output of arrays each of which is shaped (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) 

I need to get them as RGB images (32,32,3). These are the approaches tried

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

this gives a very distorted image looks like 9 images of the same item which I think is due to the reshape

image distorted

Is there a way to avoid this? I have also tried

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

which gives the following image as output empty image

Can someone please help me out? Other approaches are also welcome

Upvotes: 1

Views: 1288

Answers (1)

a_parida
a_parida

Reputation: 636

The problem is essentially the reshape command. Since in deep learning the input images are defined as [batchsize, channels, height, width] so to see the image in its proper form you should resize it to shape (3,32,32).

Here is a minimal code to get the desired output:

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)

Upvotes: 2

Related Questions