Skip to content

Instantly share code, notes, and snippets.

@josepsmartinez
Last active January 30, 2021 00:52
Show Gist options
  • Select an option

  • Save josepsmartinez/5b7d76ab78bbcffeca184ebfd1e8dcfd to your computer and use it in GitHub Desktop.

Select an option

Save josepsmartinez/5b7d76ab78bbcffeca184ebfd1e8dcfd to your computer and use it in GitHub Desktop.
Numpy array to base64 back and forth (including JSON serialization)
import numpy as np
import base64
import json
def without_serialization(arr):
b64_bytes = base64.b64encode(arr)
bytes_for_np = base64.decodebytes(b64_bytes)
arr_back = np.frombuffer(bytes_for_np, dtype=np.float32)
assert np.allclose(arr, arr_back)
def with_serialization(arr):
b64_bytes = base64.b64encode(arr)
np_bytes_for_json = b64_bytes.decode("ascii")
# test serialization
try:
json.dumps(b64_bytes)
except TypeError:
pass
json.dumps(np_bytes_for_json)
bytes_for_np = base64.b64decode(np_bytes_for_json)
arr_back = np.frombuffer(bytes_for_np, dtype=arr.dtype)
assert np.allclose(arr, arr_back)
arr = np.array([.0003248340023408243, .2500005235235], dtype=np.float32)
without_serialization(arr)
with_serialization(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment