4/16/2020

Python OpenCV Image to byte string for json transfer

code :
import cv2
import base64
import json
import numpy as np

######################################################
#read image
img = cv2.imread('./code_backup/test_img.jpg')
#cv2 to string
image_string = cv2.imencode('.jpg', img)[1]
image_string = base64.b64encode(image_string).decode()
#make string image dict
dict = {'img':image_string}
#save dict to json file
with open('./code_backup/cv2string.json', 'w') as fp:
json.dump(dict, fp, indent=5)
######################################################


######################################################
#read json
response = json.loads(open('./code_backup/cv2string.json', 'r').read())
#get image string
string = response['img']
#convert string to image
jpg_original = base64.b64decode(string)
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
img = cv2.imdecode(jpg_as_np, flags=1)
#show image
cv2.imshow('show image', img)
cv2.waitKey(0)
######################################################
..

this is input image

this is summarised json file
{ "img": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCAFoAeADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD2BP8Ag34/4JIE4P7I4/8AC617/wCTqsJ/wb4/8EiTx/wyR/5fWv8A/wAnV9nPH2x+FSwx14/t6vc+i+r4f+Q+Mk/4N7P+CQ+P+TRx/wC ........."
}

No comments:

Post a Comment