使用 python 有效地解压 mono12packed 位串格式

Effienctly unpack mono12packed bitstring format with python

我有来自相机的原始数据,它是 mono12packed 格式。这是一种交错位格式,用于在 3 个字节中存储 2 个 12 位整数以消除开销。每 3 个字节的显式内存布局如下所示:

Byte 1 = Pixel0 Bits 11-4
Byte 2 = Pixel1 Bits 3-0 + Pixel0 Bits 3-0
Byte 3 = Pixel1 Bits 11-4

我有一个文件,可以使用二进制读取从中读取所有字节,我们假设它被称为 binfile

要从我做的文件中获取像素数据:

from bitstring import BitArray as Bit

f = open(binfile, 'rb')
bytestring = f.read()
f.close()
a = []
for i in range(len(bytestring)/3): #reading 2 pixels = 3 bytes at a time
    s = Bit(bytes = bytestring[i*3:i*3+3], length = 24)
    p0 = s[0:8]+s[12:16]
    p1 = s[16:]+s[8:12]
    a.append(p0.unpack('uint:12'))
    a.append(p1.unpack('uint:12'))

这有效,但速度非常慢,我想更有效地做到这一点,因为我必须对大量数据这样做。

我的想法是,通过一次读取超过 3 个字节,我可以在转换步骤中节省一些时间,但我想不出办法。

另一个想法是,由于位以 4 个为一组,也许有一种方法可以处理半字节而不是位。

数据示例:

字节数

'\x07\x85\x07\x05\x9d\x06'

导致数据

[117, 120, 93, 105]

你试过按位运算符吗?也许这是更快的方法:

with open('binfile.txt', 'rb') as binfile:
  bytestring = list(bytearray(binfile.read()))


a = []

for i in range(0, len(bytestring), 3):
  px_bytes = bytestring[i:i+3]
  p0 = (px_bytes[0] << 4) | (px_bytes[1] & 0x0F)
  p1 = (px_bytes[2] << 4) | (px_bytes[1] >> 4 & 0x0F)
  a.append(p0)
  a.append(p1)

print a

这也输出: [117, 120, 93, 105]

希望对您有所帮助!