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

2024-04-26 00:55:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想“压缩”一个大的布尔数组的大小(Ny,Nx)。将它们转换为uint8数组(Ny,Nx//8)的最快方法是什么?在这个数组中,每个布尔平面都存储在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)

现在,这不是特别快,在我的电脑上,它需要大约77毫秒转换8个图像大小1600x2560(我想转换约25000图像)。我想这将是一个非常简单的操作,所以应该有一个闪电般的实现,对吗?我想最好的方法可能是使用numpy视图,但是numpy boolean类型也存储为一个字节,所以这不起作用。你知道吗

背景:我使用的是一种数字微镜装置,它是一种只有二进制电平的快速显示装置[0,1]。你必须提前上传所有你想显示的图案。为了节省PC和设备上的内存,设备支持上载“压缩”图像。在本例中,您上载一个uint8数组,但它将使用每个uint8字节内的每一位来计算下八个镜像的级别,而不是一个镜像。你知道吗


Tags: the方法图像imagenumpynp数组compressed