Last active
January 28, 2019 16:29
-
-
Save sscarbal/ebd2828e3807aa097f9808aaf06106fa to your computer and use it in GitHub Desktop.
Image and metadata serialization/deserialization to/from json.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from scipy import misc | |
import json | |
import cv2 | |
import time | |
import datetime as dt | |
import base64 | |
import io | |
from urllib.request import urlopen | |
import os | |
# Open an image from url | |
url = 'https://dummyimage.com/600x400/000/fff' | |
with urlopen(url) as file: | |
image = misc.imread(file) | |
''' | |
1. Serialization | |
''' | |
# Base64 encode image for transfer in json | |
jpg = cv2.imencode('.jpg', image)[1] | |
jpg_as_text = base64.b64encode(jpg).decode('utf-8') | |
# Build json object | |
data = { | |
'image': jpg_as_text, | |
'timestamp': dt.datetime.now().isoformat() | |
} | |
#Save frame as JPEG file, for debugging purpose only | |
with open("600x400.json", "w") as write_file: | |
json.dump(data, write_file) | |
''' | |
2. Deserizalization | |
''' | |
#Open and deserializae the json from disk | |
with open("600x400.json", "r") as read_file: | |
upload_data = json.load(read_file) | |
# Decode the image in the upload json | |
decoded = base64.b64decode(upload_data['image']) | |
stream = io.BytesIO(decoded) | |
image_result = misc.imread(stream) | |
misc.imshow(image_result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment