有的时候,咱们须要把一些 numpy.ndarray 对象在网络中传输,这个时候就要寻找一种高效的、适宜网络传输的序列化形式:
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
""""""
论断
论断:办法四 < 办法二 < 办法一 < 办法三
(7982)< (15130)< (41111)< (41224)