首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在memmap支持下,是否可以将磁盘上的布尔numpy数组保存为每个元素的1位?

在memmap支持下,是否可以将磁盘上的布尔numpy数组保存为每个元素的1位?
EN

Stack Overflow用户
提问于 2022-05-18 06:12:50
回答 1查看 109关注 0票数 4

是否有可能以布尔格式将numpy数组保存在磁盘上,其中每个元素只需要1位?这个答案建议使用填料位解包位,但是从文档来看,这似乎不支持内存映射。是否有一种方法可以在磁盘上存储具有memmap支持的1位arays?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-18 11:41:24

numpy不支持每个元素数组1位,我怀疑memmap有这样的特性。然而,有一个简单的解决办法使用包位。

由于您的情况不是按位随机访问,所以可以将其读取为每个元素数组1字节。

代码语言:javascript
复制
# 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]))

请注意,此解决方案可以(而且很可能会)读取额外的位。具体而言,两端最大7位。在您的例子中,它将是7x2x256位,但这仅仅是补丁的5%,所以我相信它是可以忽略不计的。

顺便说一句,这不是你的问题的答案,但是当你处理二进制掩码,如图像分割标签,压缩压缩可能会大大减少文件大小。这是可能的,它可以减少到少于8KB的每幅图像(而不是每个补丁)。您可能也需要考虑这个选项。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72283998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档