获取HDF5数据集的维度

Get the dimensions of a HDF5 dataset

本文关键字:数据集 HDF5 获取      更新时间:2023-10-16

我在我的c++程序中使用一些HDF5文件,我有一个关于H5Dopen函数的问题。是否有可能在给定的文件中获得hdf5数据集的尺寸?

hid_t file, dset;
herr_t status;
file = H5Fopen (filenameField, H5F_ACC_RDONLY, H5P_DEFAULT);
dset = H5Dopen (file, "/xField", H5P_DEFAULT);

在下一行之前,我想知道dset的维数

status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,  &readBuf[0]);

我只找到了H5Dget_storage_size,但那不适合我的情况。

有人知道怎么做吗?

为此,您需要使用以H5S为前缀的dataspace函数。

HDF5参考手册是使用这些前缀组织的,因此它有助于理解。

如何获取数据集的维度

首先,您需要使用H5Dget_space:

从数据集中获取数据空间:
hid_t dspace = H5Dget_space(dset);

如果你的数据空间是简单的(即不是null标量),那么你可以使用H5Sget_simple_extent_ndims:

获得维度数
const int ndims = H5Sget_simple_extent_ndims(dspace);

和每个维度的大小使用H5Sget_simple_extent_dims:

hsize_t dims[ndims];
H5Sget_simple_extent_dims(dspace, dims, NULL);

尺寸现在存储在dims

或者,可以这样做(如果是简单的数据空间,请参阅Simons的回答,必要时请使用bool H5::DataSpace::isSimple() const进行检查):

  #include "H5Cpp.h"
  using namespace H5;
  //[...]
  DataSpace dataspace(RANK, dims);
  //[...]
  /*
   * Get the number of dimensions in the dataspace.
   */
  const int rank = dataspace.getSimpleExtentNdims();

这一行在大多数情况下可能是多余的,因为整个任务可以在两行中完成:

  /*
   * Get the dimension size of each dimension in the dataspace and
   * store the dimentionality in ndims.
   */
  hsize_t dims_out[rank];
  const int ndims = dataspace.getSimpleExtentDims( dims_out, NULL);

函数getSimpleExtentNdims()可以作为H5::DataSpace实例的成员调用。

这些代码片段取自最新的hdf5c++参考手册的示例页(readdata.cpp)。

h5c++编译所有内容,它应该可以工作。