Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pickling an image object? [duplicate]

Tags:

python

pickle

I'm a complete novice with pickle, and I have a bunch of (about 100,000) images that need to be pickled.

They are first loaded as image object, and converted to data as following:

image = {
    'pixels': im.tostring(),
    'size': im.size,
    'mode': im.mode,
}

Now how do I pickle them into one pkl file?

like image 913
ytrewq Avatar asked Mar 18 '23 20:03

ytrewq


2 Answers

You could do it like this:

file = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(image, file)
file.close()

To read in the dictionary, you can do it like this:

file = open('data.pkl', 'rb')

image = pickle.load(pkl_file)
print image
file.close()

It is also possible to dump the data twice:

import pickle

# Write to file.
file = open("data.pkl", "wb")
pickle.dump(image1, file)
pickle.dump(image2, file)
file.close()

# Read from file.
file = open("data.pkl", "rb")
image1 = pickle.load(file)
image2 = pickle.load(file)
file.close()
like image 121
miindlek Avatar answered Mar 29 '23 11:03

miindlek


Just call pickle.dump, the same way you would for anything else. You have a dict whose values are all simple types (strings, tuples of a couple numbers, etc.). The fact that it came from an image is irrelevant.

If you have a bunch of them, presumably they're stored in a list or some other structure, and you can pickle a list of pickleable objects.

So:

with open('data.pkl', 'wb') as f:
    pickle.dump(images, f)
like image 28
abarnert Avatar answered Mar 29 '23 11:03

abarnert