微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:读取/解包 12 位小端打包数据的快速方法

如何解决Python:读取/解包 12 位小端打包数据的快速方法

如何加快在 Python 中读取 12 位小端打包数据的速度?

以下代码基于 https://stackoverflow.com/a/37798391/11687201,可以运行,但耗时太长。

import bitstring
import numpy as np

# byte_string read from file contains 12 bit little endian packed image data
# b'\xAB\xCD\xEF' -> pixel 1 = 0x0DAB,pixel 2 = Ox0EFC
# width,height equals image with height read
image = np.empty(width*height,np.uint16)

ic = 0
ii = np.empty(width*height,np.uint16)
for oo in range(0,len(byte_string)-2,3):    
    aa = bitstring.BitString(byte_string[oo:oo+3])
    aa.byteswap()
    ii[ic+1],ii[ic] = aa.unpack('uint:12,uint:12')
    ic=ic+2

解决方法

这应该会好一点:

for oo in range(0,len(byte_string)-2,3):
    (word,) = struct.unpack('<L',byte_string[oo:oo+3] + b'\x00')
    ii[ic+1],ii[ic] = (word >> 12) & 0xfff,word & 0xfff
    ic += 2

它非常相似,但不是使用非常慢的 bitstring,而是使用对 struct.unpack 的单个调用一次提取 24 位(用零填充,以便可以将其读取为长),然后进行一些位掩码以提取两个不同的 12 位部分。

,

我找到了一个解决方案,它在我的系统上执行速度比上面提到的解决方案 https://stackoverflow.com/a/65851364/11687201 快得多,这已经是一个很大的改进(使用问题中的代码需要 2 秒而不是 2 分钟)。 使用下面的代码加载我的一个图像文件大约需要 45 毫秒,而不是上述解决方案的大约 2 秒。

import numpy as np
import math

image = np.frombuffer(byte_string,np.uint8)
num_bytes = math.ceil((width*height)*1.5)
num_3b = math.ceil(num_bytes / 3)
last = num_3b * 3
image = image[:last]
image = image.reshape(-1,3)
image = np.hstack( (image,np.zeros((image.shape[0],1),dtype=np.uint8)) )
image.dtype='<u4' # 'u' for unsigned int
image = np.hstack( (image,dtype=np.uint8)) )
image[:,1] = (image[:,0] >> 12) & 0xfff
image[:,0] = image[:,0] & 0xfff
image = image.astype(np.uint16)
image = image.reshape(height,width)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。