如何正确选择所需的数据并从二进制文件中丢弃不需要的数据



我正在做一个项目,我正在尝试将旧的 16 位二进制数据文件转换为 32 位数据文件以供以后使用。

直接转换没有问题,但后来我注意到我需要从数据文件中删除标头数据。

数据由 8206 字节长的帧组成,每帧由14 字节长的标头和 4096 字节长的数据块组成,根据文件的不同,每个文件中有 70313 或70312

我找不到一种巧妙的方法来查找所有标题并删除它们并仅将数据块保存到新文件中。

所以我做了:

results_array = np.empty([0,1], np.uint16)
for filename in file_list:
num_files += 1
# read data from file as 16bit's and save it as 32bit
data16 = np.fromfile(data_dir + "/" + filename, dtype=np.uint16)
filesize = np.prod(data16.shape)
if filesize == 288494239:
total_frames = 70313
#total_frames = 3000
else:
total_frames = 70312
#total_frames = 3000
frame_count = 0
chunksize = 4103
with open(data_dir + "/" + filename, 'rb') as file:
while frame_count < total_frames:
frame_count += 1
read_data = file.read(chunksize)
if not read_data:
break
data = read_data[7:4103]
results_array = np.append(results_array,data)
converted = np.frombuffer(results_array, np.uint16)
print(str(frame_count) + "/" + str(total_frames))
converted = np.frombuffer(results_array, np.uint16)
data32 = converted.astype(dtype=np.uint32) * 256

它有效(我认为至少可以(,但它非常非常慢。

所以问题是,有没有办法更快地完成上述操作,也许是 numpy 中的一些内置功能或其他东西?

提前致谢

终于设法破解了这个,它比最初的方法快 100 倍:)

data = np.fromfile(read_dir + "/" + file, dtype=np.int16)
frames = len(data) // 4103 # framelenght
# Reshape into array such that each row is a frame
data = np.reshape(data[:frames * 4103], (frames, 4103))
# Remove headers and convert to int32
data = data[:, 7:].astype(np.int32) * 256

相关内容

最新更新