Skip to content

Instantly share code, notes, and snippets.

@sreeragh-ar
Last active June 30, 2023 06:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sreeragh-ar/70205db3a43badbfa69f758faa898be3 to your computer and use it in GitHub Desktop.
Save sreeragh-ar/70205db3a43badbfa69f758faa898be3 to your computer and use it in GitHub Desktop.
#pickle dict with image in Python2 (2.7.6 used)
frame = cv2.imread('input.jpg')
img_str = cv2.imencode('.jpg', frame)[1].tostring()
data = {'img': img_str}
with open('pickledObj.pkl', 'wb') as outfile:
pickle.dump(data, outfile)
# unpickle in Python3 (Python 3.4.3 used for testing) using encoding=latin1
with open('pickledObj.pkl', 'rb') as f:
data_dict = pickle.load(f, encoding='latin1')
img_str = data_dict['img']
img = np.fromstring(img_str, dtype='uint8')
img = cv2.imdecode(img, cv2.IMREAD_UNCHANGED)
cv2.imwrite('latin_output.jpg', img)) # This will be a corrupted image
# unpickle in Python3 encoding=bytes
with open('pickledObj.pkl', 'rb') as f:
data_dict = pickle.load(f, encoding='bytes')
img_str = data_dict[b'img']
img = np.fromstring(img_str, dtype='uint8')
img = cv2.imdecode(img, cv2.IMREAD_UNCHANGED)
cv2.imwrite('output.jpg', img) # Retrieves the original image
@sreeragh-ar
Copy link
Author

Issues when unpickling a Python2 pickle object in Python3

https://stackoverflow.com/a/47882939/5774004

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment