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

标签 python numpy casting binary

我想“压缩”一大堆大小为 (Ny, Nx) 的 bool 值。将它们转换为大小为 (Ny, Nx//8) 的 uint8 数组的最快方法是什么,其中每个 bool 平面都存储在 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 上,转换 8 个大小为 1600x2560 的图像大约需要 77 毫秒(我想转换约 25000 个图像)。我想这将是一个非常简单的操作,所以应该有一个闪电般快速的实现,对吗?我认为最好的方法可能是使用 numpy View ,但 numpy bool 类型也存储为字节,因此这是行不通的。

上下文:我正在使用数字微镜设备,它是某种仅具有二进制级别 [0,1] 的快速显示器。您必须提前上传所有想要显示的图案。为了节省 PC 和设备上的内存,设备支持上传“压缩”图像。在本例中,您上传一个 uint8 数组,但它将使用每个 uint8 字节内的每一位来计算接下来八个镜像的级别,而不是仅一个。

最佳答案

使用np.packbits:

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

关于python - 如何将 bool 类型的 numpy 数组压缩为 uint8,大小为 1/8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58875683/

相关文章:

Python、Selenium Webdriver : Spans are not loaded for Firefox driver

python - 用平均值填充 nan 值的更快方法

python - 使用 numpy.loadtxt 解析包含 HH :MM:SS. mmm 次的数据矩阵

将字符串转换为 long long C?

c# - 为什么会出现此 "Unable to cast object of type"异常?

Python 函数参数传递序列

python - 你如何比较像素?

python - 如何剪辑python numpy复数数组元素的实部和虚部

python - 不同长度列中变量之间的绝对差

c# - LINQ 以及如何返回特定类型的列表