如何将大小为1/8的bool类型的numpy数组压缩为uint8

时间:2019-11-15 11:03:45

标签: python numpy casting binary

我想“压缩”大小为Ny,Nx的大量布尔值。将它们转换为大小为(Ny,Nx // 8)的uint8数组的最快方法是什么,每个布尔平面都存储在uint8的下一位?

到目前为止,我已经实现了该实现:


import numpy as np

def compressImage(imdata):

    imdatashape = imdata.shape
    imdata_4d = imdata

    imdata_4d.shape = *imdatashape[:-1], imdatashape[-1]//8,8
    compressed_image = np.zeros(imdata_4d.shape[:-1], np.uint8)
    # take every image and add it with the right bit shift to the final image
    for i in range(8):
        compressed_image += imdata_4d[...,i] << i
    return compressed_image


imdata = np.random.randint(0,1, (500, 1600,2560), dtype=np.uint8)
imcompressed = compressImage(imdata)

现在,这并不是特别快,在我的PC上,转换八张大小为1600x2560的图像(我想转换〜25000张图像)大约需要77毫秒。我想这将是一个非常简单的操作,因此应该对此实现一个闪电般的实现,对吧?我认为最好的方法可能是使用numpy视图,但是numpy布尔类型也存储为字节,因此无法正常工作。

上下文:我正在使用数字微镜设备,这是一种只有二进制级别[0,1]的快速显示。您必须预先上传所有要显示的图案。为了节省PC和设备上的内存,设备支持上传“压缩”图像。在这种情况下,您将上传一个uint8数组,但是它将使用每个uint8字节内的每一位来确定接下来的八个镜像的级别,而不只是一个镜像。

1 个答案:

答案 0 :(得分:2)

使用np.packbits

np.packbits(imdata,axis=-1,bitorder="little")