如何创建包含24位整数的Numpy dtype?

时间:2012-08-22 19:41:06

标签: python numpy

我有一个二进制文件,其记录结构为400个24位有符号大端整数,后跟一个16位大端符号短路。我想做的是:

from numpy import dtype , fromfile
record_dtype = dtype([('samples','>i3',(400,)),('marker','>i2')])
data = fromfile('binary_file.dat',dtype=record_dtype)

不幸的是,我得到的是:

TypeError: data type not understood

回应'> i3'。如何定义dtype以24位二进制数读取?

1 个答案:

答案 0 :(得分:7)

我有大约一个太字节文件,它是24位四通道PCM。

我当然不想触摸除了我想要的任何部分,所以我所做的就是这样:

import numpy as np
from numpy.lib.stride_tricks import as_strided

rawdatamap = np.memmap('4ch24bit800GBdatafile.pcm', dtype=np.dtype('u1'),mode='r')

# in case of a truncated frame at the end
usablebytes = rawdatamap.shape[0]-rawdatamap.shape[0]%12

frames = int(usablebytes/12)
rawbytes = rawdatamap[:usablebytes]

realdata = as_strided(rawbytes.view(np.int32), strides=(12,3,), shape=(frames,4))

someusefulpart = realdata[hugeoffset:hugeoffset+smallerthanram]&0x00ffffff

这从文件中复制了smallerthanram个字节的内存。

注意字节掩码!你需要它来切断32位字的最高有效字节 - 这将是属于前一个样本的垃圾。

您也可以将它应用于这样的单个数据:

scaled_ch2_datum_at_framenum = scalefactor*(realdata[framenum,1]&0x00ffffff)-shiftoffset

它有点乱,但现在好了。

实际上你可能需要64位系统才能做到这一点。

NB。这适用于小端数据。要处理大端,您需要在视图中使用big-endian dtype,并将...&0x00ffffff替换为...&ffffff00>>8

相关问题