将块写入文件:
In [117]: dat = np.random.randint(0,1028,80*80).astype(np.uint16)
In [118]: dat.tofile('test.dat')
In [119]: dat
Out[119]: array([266, 776, 458, ..., 519, 38, 840], dtype=uint16)
按照您的方式导入:
In [120]: import struct
In [121]: with open('test.dat','rb') as f:
...: frame = np.array(struct.unpack("H"*6400,f.read(12800)))
...:
In [122]: frame
Out[122]: array([266, 776, 458, ..., 519, 38, 840])
导入与fromfile
In [124]: np.fromfile('test.dat',count=6400,dtype=np.uint16)
Out[124]: array([266, 776, 458, ..., 519, 38, 840], dtype=uint16)
比较时间:
In [125]: %%timeit
...: with open('test.dat','rb') as f:
...: ...: frame = np.array(struct.unpack("H"*6400,f.read(12800)))
...:
1000 loops, best of 3: 898 µs per loop
In [126]: timeit np.fromfile('test.dat',count=6400,dtype=np.uint16)
The slowest run took 5.41 times longe....
10000 loops, best of 3: 36.6 µs per loop
fromfile
速度要快得多。
时间为struct.unpack
, 没有np.array
为 266 微秒;只是为了f.read
, 23.所以这就是unpack
加上更通用和强大的np.array
这需要更长的时间。文件读取本身不是问题。 (np.array
可以处理多种输入,列表的列表,对象的列表等,因此必须花费更多的时间来解析和评估输入。)
稍微快一点的变体fromfile
是你的阅读加frombuffer
:
In [133]: with open('test.dat','rb') as f:
...: frame3 = np.frombuffer(f.read(12800),dtype=np.uint16)