Sometimes, we need to transmit some numpy.ndarray objects in the network. At this time, we need to find an efficient serialization method suitable for network transmission:
from mark import BASE_DIR
from numpy import ndarray
import numpy
import pickle
img1 = numpy.array([i for i in range(5120)])
# 方式一: 使用 pickle 序列化 numpy.ndarray
with open(BASE_DIR/'testing'/'001.bin', 'wb') as f:
img1: ndarray
f.write(pickle.dumps(img1))
# --- 结果 41111 bytes
# 方法二: 使用 pickle 序列化 python 的 list 对象
with open(BASE_DIR/'testing'/'002.bin', 'wb') as f:
ins: list[int] = img1.tolist()
f.write(pickle.dumps(ins))
# --- 结果 15130 bytes
# 方法三: 使用 numpy 的 savez 序列化 numpy.ndarray
numpy.savez(BASE_DIR/'testing'/'numpy_savez_test', img1)
# --- 结果 41224 bytes
# 方法四: 使用 numpy 的 savez_compressed (带压缩功能) 序列化 numpy.ndarray
numpy.savez_compressed(BASE_DIR/'testing'/'numpy_savez_compressed_test', img1)
numpy.load(BASE_DIR/'testing'/'numpy_savez_compressed_test')
# --- 结果 7982 bytes
"""
"""
in conclusion
结论:
方法四 < 方法二 < 方法一 < 方法三
(7982)< (15130)< (41111)< (41224)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。