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?
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()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With