是否可以将numpy数组以布尔格式保存在磁盘上,其中每个元素只需要1位?This answer建议使用packbitsunpackbits,但从文档来看,这似乎不支持内存映射.有没有一种方法可以通过memmap支持在磁盘上存储1bit aray?

要求memmap的原因:我正在全高清(1920x1080)图像数据库上训练我的神经网络,但每次迭代我都会随机裁剪出256x256个补丁.因为读取完整图像很耗时,所以我使用memmap只读取所需的补丁.现在,我想在我的图像中使用一个二进制掩码,因此这是一个要求.

推荐答案

numpy不支持每元素1位的数组,我怀疑memmap是否有这样的功能.

由于您的大小写不是按位随机访问,所以可以按每个元素数组读取1字节.

# A binary mask represented as an 1 byte per element array.
full_size_mask = np.random.randint(0, 2, size=[1920, 1080], dtype=np.uint8)

# Pack mask vertically.
packed_mask = np.packbits(full_size_mask, axis=0)

# Save as a memmap compatible file.
buffer = np.memmap("./temp.bin", mode='w+',
                   dtype=packed_mask.dtype, shape=packed_mask.shape)
buffer[:] = packed_mask
buffer.flush()
del buffer

# Open as a memmap file.
packed_mask = np.memmap("./temp.bin", mode='r',
                        dtype=packed_mask.dtype, shape=packed_mask.shape)

# Rect where you want to crop.
top = 555
left = 777
width = 256
height = 256

# Read the area containing the rect.
packed_top = top // 8
packed_bottom = (top + height) // 8 + 1
packed_patch = packed_mask[packed_top:packed_bottom, left:left + width]

# Unpack and crop the actual area.
patch_top = top - packed_top * 8
patch_mask = np.unpackbits(packed_patch, axis=0)[patch_top:patch_top + height]

# Check that the mask is cropped from the correct area.
print(np.all(patch_mask == full_size_mask[top:top + height, left:left + width]))

请注意,此解决方案可以(并且可能会)读取额外的位.

顺便说一句,这并不是对您问题的回答,但当您处理二进制掩码(如用于图像分割的标签)时,使用zip压缩可能会大大减少文件大小.

Python相关问答推荐

在Python中对分层父/子列表进行排序

如果条件为真,则Groupby.mean()

韦尔福德方差与Numpy方差不同

处理(潜在)不断增长的任务队列的并行/并行方法

如何使用html从excel中提取条件格式规则列表?

不理解Value错误:在Python中使用迭代对象设置时必须具有相等的len键和值

如何更改分组条形图中条形图的 colored颜色 ?

根据列值添加时区

当递归函数的返回值未绑定到变量时,非局部变量不更新:

不允许访问非IPM文件夹

Python逻辑操作作为Pandas中的条件

Pandas GroupBy可以分成两个盒子吗?

如何从需要点击/切换的网页中提取表格?

(Python/Pandas)基于列中非缺失值的子集DataFrame

获取git修订版中每个文件的最后修改时间的最有效方法是什么?

Python:从目录内的文件导入目录

分解polars DataFrame列而不重复其他列值

上传文件并使用Panda打开时的Flask 问题

我可以同时更改多个图像吗?

为什么fizzbuzz在两个数字的条件出现在一个数字的条件之后时不起作用?