将交错数据拆分为不同通道的 np.array?



我有一个二进制文件,其中包含交错数据;下面是一个Python脚本,它将生成一个示例:

test-np-array-il-split-01.py

#!/usr/bin/env python2
# (also works with python3)
# generate a test binary file with interleaved floats
thebinfilename = "il3ch.binfile"
import struct
# https://docs.python.org/2/library/struct.html :  "=" native; "<" little-endian; ">" big-endian
with open(thebinfilename, 'wb') as f:
for ix in range(10):
decremain = ix/100.0;
for ic in range(3):
thischannum = ic+1 + decremain;
print(thischannum)
f.write(struct.pack("=f", thischannum))

基本上,只需运行python test-np-array-il-split-01.py,您将在同一目录中il3ch.binfile获得一个二进制文件。这个文件基本上有这样的浮点数序列:

1.0, 2.0, 3.0, 1.01, 2.01, 3.01, 1.02, 2.02, 3.02, 1.03, 2.03, 3.03, 1.04, 2.04, 3.04, 1.05, 2.05, 3.05, 1.06, 2.06, 3.06, 1.07, 2.07, 3.07, 1.08, 2.08,

3.08, 1.09, 2.09, 3.09

。存储为二进制浮点数。

基本上,我想将单个通道数据作为单独的 numpy 数组获取,其中通道将是:

  • Ch1: 1.0, 1.01, 1.02, 1.03, 1.04, ...
  • Ch2: 2.0, 2.01, 2.02, 2.03, 2.04, ...
  • Ch3: 3.0, 3.01, 3.02, 3.03, 3.04, ...

因此,我尝试编写以下脚本(将其放在与test-np-array-il-split-01.pyil3ch.binfile相同的文件夹中):

test-np-array-il-split-02.py

#!/usr/bin/env python2
# (also works with python3)
# read a test binary file with interleaved floats
thebinfilename = "il3ch.binfile"
import numpy as np
dt = np.dtype( [ ('CH1', '<f4'), ('CH2', '<f4'), ('CH3', '<f4') ] )
bin_np_arr = np.fromfile(thebinfilename, dtype=dt)
print(bin_np_arr.shape) # (10,)
print(bin_np_arr)
# [(1.  , 2.  , 3.  ) (1.01, 2.01, 3.01) (1.02, 2.02, 3.02)
#  (1.03, 2.03, 3.03) (1.04, 2.04, 3.04) (1.05, 2.05, 3.05)
#  (1.06, 2.06, 3.06) (1.07, 2.07, 3.07) (1.08, 2.08, 3.08)
#  (1.09, 2.09, 3.09)]
ch1, ch2, ch3 = bin_np_arr[:][0], bin_np_arr[:][1], bin_np_arr[:][2]
print(ch1) # (1., 2., 3.) # -> however, I want 1.0, 1.01, 1.02, 1.03 ... etc here!

所以,好消息是通过使用np.dtype规范,我可以在数据中强加一种结构 - 但是,作为输出,我得到了 (CH1、CH2、CH3) 元组的 np.array,我真的不知道我需要做什么,来拆分这个 np.array。

所以我的问题是:如何将bin_np_arrnp.array 拆分为三个单独的 np.array,它们将对应于各个通道数据?另外,我是否应该以与文件不同的方式读取bin_np_arr(例如,它有不同的.shape),因此它更适合这种"每通道"拆分?

使用结构化数组时,可以使用语法['<field name>']访问每个字段对应的数组。在您的情况下,您可以简单地执行以下操作:

ch1, ch2, ch3 = bin_np_arr['CH1'], bin_np_arr['CH2'] and bin_np_arr['CH3']

最新更新