python - h5py:如何在不将所有内容加载到内存的情况下索引多个大型 HDF5 文件

标签 python h5py

这是一个关于同时处理多个 HDF5 数据集并尽可能将它们视为一个数据集的问题。

我有多个.h5 文件,每个文件包含数万张图片。让我们调用文件

file01.h5
file02.h5
file03.h5

我现在想创建一个列表或数组,其中包含指向所有三个文件的所有图像的“指针”,而不实际加载图像。

这是我目前所拥有的:

我首先打开所有文件:

file01 = h5py.File('file01.h5', 'r')
file02 = h5py.File('file02.h5', 'r')
file03 = h5py.File('file03.h5', 'r')

并将他们的图像数据集添加到列表中:

images = []
images.append(file01['images'])
images.append(file02['images'])
images.append(file03['images'])

其中 file01['images'] 是一个 HDF5 数据集,其形状例如(52722, 3, 160, 320),即 52722 张图像。到目前为止一切都很好,还没有任何内容被加载到内存中。现在我想将这三个单独的图像列表合二为一,这样我就可以像处理一个大型数据集一样处理它。我试着这样做:

images = np.concatenate(images)

这就是它的破绽。一旦我连接了三个 HDF5 数据集,它实际上将图像加载为 Numpy 数组并且我用完了内存。

解决这个问题的最佳方法是什么?

我需要一个解决方案,使我能够像对一个数据集一样对三个数据集进行 Numpy 切片和索引。

例如,假设每个数据集包含 50,000 张图像,我想加载每个数据集的第三张图像,我需要一个列表 images 允许我将这些图像索引为

batch = images[[2, 50002, 100002]]

最佳答案

HDF5 引入了“虚拟数据集 (VDS)”的概念。 但是,这不适用于 1.10 之前的版本。

我没有使用 VDS 功能的经验,但 h5py文档更详细,h5py git 存储库有一个示例文件 here :

'''A simple example of building a virtual dataset.
This makes four 'source' HDF5 files, each with a 1D dataset of 100 numbers.
Then it makes a single 4x100 virtual dataset in a separate file, exposing
the four sources as one dataset.
'''

import h5py
import numpy as np

# Create source files (1.h5 to 4.h5)
for n in range(1, 5):
    with h5py.File('{}.h5'.format(n), 'w') as f:
        d = f.create_dataset('data', (100,), 'i4')
        d[:] = np.arange(100) + n

# Assemble virtual dataset
layout = h5py.VirtualLayout(shape=(4, 100), dtype='i4')

for n in range(1, 5):
    filename = "{}.h5".format(n)
    vsource = h5py.VirtualSource(filename, 'data', shape=(100,))
    layout[n - 1] = vsource

# Add virtual dataset to output file
with h5py.File("VDS.h5", 'w', libver='latest') as f:
    f.create_virtual_dataset('data', layout, fillvalue=-5)
    print("Virtual dataset:")
    print(f['data'][:, :10])

可以在 HDF group 上找到更多详细信息链接到 pdf .图 1 很好地说明了这个想法。

关于python - h5py:如何在不将所有内容加载到内存的情况下索引多个大型 HDF5 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48856981/

相关文章:

Python icmp 套接字服务器(不是 tcp\udp)

Python:不在网格数据上的双变量样条

python - 使用 pandas 合并时如何保留索引

python - 写入过程完成后 HDF5 文件内容消失

python - 如何在 h5py 中使用 HDF5 尺寸刻度

python - 如何循环遍历 hdf5 文件中的所有键和值并确定哪些包含数据?

python - 象棋的python或C

Python ctypes - 访问 Structure.value 中的数据字符串失败

python - 将 numpy 数组列表保存到磁盘上

python - 使用 python 库 h5py 获取 h5 文件中的所有键及其层次结构