环境
- Ubuntu16.04
- python 3.x
序列化、反序列化
将复杂的‘数据结构/对象’序列化、反序列化
import pickle
import base64
import json
a = [[1, ['a']], [2, ['a', 'c']], [3, ['d']], [4, ['b']]] #可以是图像cv2的image的对象,或者组合的更复杂的数据结构
#复杂结构/对象转json字符串(序列化)
c = pickle.dumps(a) #序列化,转为byte
d = base64.b64encode(c).decode() #使用base64转换byte为str
print(type(d))
json_res = {"a": d}
json_str = json.dumps(json_res)# 再转化为json的字符串形式
print(json_str)
print(type(json_str))
#json字符串转回原始结构(反序列化)
json_res = json.loads(json_str) #json字符串转为json结构
e = base64.b64decode(json_res["a"]) #字符串转为byte
t = pickle.loads(e) #byte反序列化转为‘复杂结构/对象’
print(t)
print(type(t))
输出:
<class 'str'>
{"a": "gANdcQAoXXEBKEsBXXECWAEAAABhcQNhZV1xBChLAl1xBShoA1gBAAAAY3EGZWVdcQcoSwNdcQhYAQAAAGRxCWFlXXEKKEsEXXELWAEAAABicQxhZWUu"}
<class 'str'>
[[1, ['a']], [2, ['a', 'c']], [3, ['d']], [4, ['b']]]
<class 'list'>
把图像cv2的数据对象与字符串互相转化
import pickle
import base64
import json
import cv2
a = cv2.imread('1.jpg')
#图像cv2的数据对象转json字符串(序列化)
c = pickle.dumps(a)
d = base64.b64encode(c).decode()
print(type(d))
json_res = {"a": d}
json_str = json.dumps(json_res)
#print(json_str)
print(type(json_str))
#json字符串转回原始图片对象(反序列化)
json_res = json.loads(json_str)
e = base64.b64decode(json_res["a"])
t = pickle.loads(e)
print(t)
print(type(t))
输出:
<class 'numpy.ndarray'>
<class 'str'>
<class 'str'>
[[[193 207 219]
[192 206 218]
[188 202 214]
...
[191 205 217]
[187 201 213]
[189 203 215]]
[[190 204 216]
[192 206 218]
[188 202 214]
...
[189 203 215]
[190 204 216]
[192 206 218]]
[[191 205 217]
[193 207 219]
[189 203 215]
...
[189 203 215]
[190 204 216]
[191 205 217]]
...
[[198 203 212]
[197 202 211]
[196 201 210]
...
[200 205 214]
[201 206 215]
[201 206 215]]
[[195 200 209]
[196 201 210]
[196 201 210]
...
[196 201 210]
[200 205 214]
[201 206 215]]
[[190 195 204]
[195 200 209]
[199 204 213]
...
[196 201 210]
[201 206 215]
[202 207 216]]]
<class 'numpy.ndarray'>
str、byte互相转换
a = "人工智能"
print(a)
byte_a = a.encode(encoding="utf-8")#str转byte
print(byte_a)
print(type(byte_a))
str_a = byte_a.decode(encoding="utf-8")#byte转str
print(str_a)
print(type(str_a))
输出:
人工智能
b'\xe4\xba\xba\xe5\xb7\xa5\xe6\x99\xba\xe8\x83\xbd'
<class 'bytes'>
人工智能
<class 'str'>
该博客介绍了在Ubuntu16.04和Python 3.x环境下的操作,包括对复杂数据结构/对象进行序列化和反序列化,还涉及图像cv2的数据对象与字符串的互相转化,以及str和byte的互相转换。
2017

被折叠的 条评论
为什么被折叠?



