将hdf5文件合并成单个数据集

5
我有很多hdf5文件,每个文件中只有一个数据集。我想将它们合并成一个数据集,使数据在同一卷中(每个文件都是图像,我想要一个大的时间序列图像)。
我编写了一个Python脚本,将数据提取为numpy数组,存储它们,然后尝试将其写入新的h5文件。但是,这种方法行不通,因为合并的数据使用的RAM超过了我的32 GB。
我还尝试使用h5copy,即命令行工具。
h5copy -i file1.h5 -o combined.h5 -s '/dataset' -d '/new_data/t1'
h5copy -i file2.h5 -o combined.h5 -s '/dataset' -d '/new_data/t2'

这个方法可以实现,但会导致新文件中存在许多数据集,而不是将所有数据集串联在一起。
1个回答

2
尽管您无法直接向hdf5数据集追加行,但在创建数据集时使用maxshape关键字可以使您受益,从而可以“调整”数据集以容纳新数据。(请参见http://docs.h5py.org/en/latest/faq.html#appending-data-to-a-dataset
假设数据集的列数始终相同,则您的代码最终将类似于以下内容:
import h5py

output_file = h5py.File('your_output_file.h5', 'w')

#keep track of the total number of rows
total_rows = 0

for n, f in enumerate(file_list):
  your_data = <get your data from f>
  total_rows = total_rows + your_data.shape[0]
  total_columns = your_data.shape[1]

  if n == 0:
    #first file; create the dummy dataset with no max shape
    create_dataset = output_file.create_dataset("Name", (total_rows, total_columns), maxshape=(None, None))
    #fill the first section of the dataset
    create_dataset[:,:] = your_data
    where_to_start_appending = total_rows

  else:
    #resize the dataset to accomodate the new data
    create_dataset.resize(total_rows, axis=0)
    create_dataset[where_to_start_appending:total_rows, :] = your_data
    where_to_start_appending = total_rows

output_file.close()

什么是从 f 获取数据? - user6038900
这个取决于你需要从每个文件中获取数据的命令或步骤,它也会因文件类型而异。例如,如果你正在处理一系列HDF5格式的文件,你需要使用h5py.File创建一个文件对象,然后使用类似file_object ["dataset_name"] [slice]的方法从文件中读取数据。 - Heather QC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接