1. np.save() 报错,np.load() 加载
使用下面这句话保存
np.save('pose_det_results_list.npy',pose_det_results_list)
下面这句加载
pose_det_results_list = np.load('pose_det_results_list.npy')
报错
Traceback (most recent call last):
File "demo/ans.py", line 2, in <module>
pose_det_results_list = np.load('pose_det_results_list.npy')
File "/home/cv/.conda/envs/mm/lib/python3.7/site-packages/numpy/lib/npyio.py", line 441, in load
pickle_kwargs=pickle_kwargs)
File "/home/cv/.conda/envs/mm/lib/python3.7/site-packages/numpy/lib/format.py", line 743, in read_array
raise ValueError("Object arrays cannot be loaded when "
ValueError: Object arrays cannot be loaded when allow_pickle=False
根据报错ValueError: Object arrays cannot be loaded when allow_pickle=False
,修改为
np.save('pose_det_results_list.npy',pose_det_results_list,allow_pickle=True) ## 保存
pose_det_results_list = np.load('pose_det_results_list.npy',allow_pickle=True) ## 加载
numpy版本>1.16.2后新加了allow_pickle
关键字,且默认值为False
,所以使用的时候需要设为True
2. 保存、读取npz格式文件
2.1 np.savez(file, *args, **kwds)
参数:
file
保存的文件名args
保存的数组。数组在文件中的名字为“arr_0”, “arr_1”…kwds
关键字参数。数组在文件中的名字为相应的关键字。推荐这种保存方式
参考官方文档
np.savez_compressed()
与np.savez()
使用方法相同,保存成了压缩的形式
2.2 npz格式文件的读取
np.load(‘test.npz’, allow_pickle=True)
If the file is a .npz file, then a dictionary-like object is returned, containing {filename: array} key-value pairs, one for each file in the archive.
import numpy as np
def save_file():
a = np.array([1,2,3])
b = np.array([10,20,30])
# np.savez_compressed('test.npz',a=a,b=b)
np.savez('test.npz',a=a,b=b)
print('Saved ')
def load_file():
print('Loading .......')
res = np.load('test.npz', allow_pickle=True)
print(res)
print(res.files)
a = res['a']
print(a)
save_file()
load_file()
输出
Saved
Loading .......
<numpy.lib.npyio.NpzFile object at 0x000002C089466A58>
['a', 'b']
[1 2 3]
3. 保存、读取二进制形式文件
3.1 保存
ndarray.tofile()
3.2 读取
numpy.fromfile(file, dtype=float,....)
读取的时候需要指定dtype
与保存时的数据类型一致。否则读出的数据会有问题
读出的数组是一维数组,还原会原始数据形状,需要reshape
def save_binary_file():
a = np.array([[1,2,3],[10,20,30]])
print('待保存数据',a,'\n shape:',a.shape,'\n******dtype********* ',a.dtype)
a.tofile('binary') ## 保存数组a到'binary文件中'
print('Saved ')
def read_binary_file():
print('loading file ...')
data_path = 'binary'
print('不指定数据类型')
data = np.fromfile(data_path) ## 加载数据并指定类型
print(data.shape)
print(data)
print('指定数据类型为 ******* np.int32 *****')
data = np.fromfile(data_path, dtype=np.int32)
print(data.shape)
print(data)
save_binary_file()
read_binary_file()
输出
待保存数据 [[ 1 2 3]
[10 20 30]]
shape: (2, 3)
******dtype********* int32
Saved
loading file ...
不指定数据类型
(3,)
[4.24399158e-314 2.12199579e-313 6.36598737e-313]
指定数据类型为 ******* np.int32 *****
(6,)
[ 1 2 3 10 20 30]