import base64 import numpy as np def img_to_json(img): return { 'data': base64.b64encode(img.tobytes()).decode('utf8'), 'shape': list(img.shape) } def json_to_img(img_json): buf = base64.b64decode(img_json['data']) shape = img_json['shape'] return np.frombuffer(buf, dtype=np.uint8).reshape(*shape)