【问题标题】:How many datasets in one hdf5 file一个 hdf5 文件中有多少个数据集
【发布时间】:2017-10-02 16:10:05
【问题描述】:

我正在使用 MATLAB 的函数 h5write 将双变量 foo 写入名为 saved_foos.h5 的 hdf5 文件。我有一个循环,它在每次迭代中更改 foo,我每次都将它保存在同一个 hdf5 文件中,但保存在另一个数据集中,该数据集中根据当前的迭代次数命名。

之后,我在带有H5Cpp库的C++程序中读取了每个数据集(每次迭代)的数据,如下所示:

#include "H5Cpp.h"
using namespace H5;

double readDouble(std::string dir, std::string file, std::string s_dataset) {
    if (!fexists((dir + file + std::string(".h5")).c_str())) {
        throw std::runtime_error((std::string("File ") + dir + file + std::string(".h5 does not exist.")).c_str());
    }
    H5File file_h(dir + file + std::string(".h5"), H5F_ACC_RDONLY);
    DataSet dataset = file_h.openDataSet(s_dataset);
    DataSpace dataspace = dataset.getSpace();
    int rank = dataspace.getSimpleExtentNdims();
    hsize_t *dims_out = new hsize_t[rank];
    dataspace.getSimpleExtentDims(dims_out, NULL);
    if (rank>=2 && (dims_out[0] * dims_out[1] != 1)) {
        throw std::runtime_error("Requested dataset is not a scalar double value.");
    }
    double data;
    dataset.read(&data, PredType::NATIVE_DOUBLE);
    delete dims_out;
    return data;
}

但是如何确定给定的 hdf5 文件中存储了多少数据集?

【问题讨论】:

    标签: c++ matlab hdf5


    【解决方案1】:

    遍历文件

    您似乎想列出文件中的数据集。 Here 是一个非常完整的示例,对于您的问题来说太过分了。为了帮助理解它,我将解释相关的代码会话:

    C-API 函数H5Literate 用于遍历组中的所有对象。

    /*
     * Use iterator to see the names of the objects in the file
     * root directory.
     */
    cout << endl << "Iterating over elements in the file" << endl;
    herr_t idx = H5Literate(file->getId(), H5_INDEX_NAME, H5_ITER_INC, NULL,    file_info, NULL);
    cout << endl;
    

    file_info 是一个回调函数:

    /*
     * Operator function.
     */
    herr_t
    file_info(hid_t loc_id, const char *name, const H5L_info_t *linfo, void *opdata)
    {
        hid_t group;
        group = H5Gopen2(loc_id, name, H5P_DEFAULT);
        cout << "Name : " << name << endl; // Display the group name.
        H5Gclose(group);
        return 0;
    }
    

    在您的情况下,其他迭代函数而不是 H5Literate 可能更合适。请找到它here。遍历文件的纯 C-API 示例可以在 here 找到。

    只获取数字

    如果所有数据集都存储在根目录下并且它们的名称格式是已知的。有一个更简单的解决方案来获取数据集的数量:

        hsize_t  num_obj;
        H5Gget_num_objs(file->getId(), &num_obj); // if success, num_obj will be assigned the number of objects in the group
    

    【讨论】:

    • 我使用了您提供的第一个示例中描述的 file_info 函数,但是我没有得到任何输出。我会得到的唯一消息是`迭代文件中的元素`。我也无法调试它。我在 file_info 函数中设置了一个断点,但程序永远不会停在那里。似乎从未调用过该函数。
    猜你喜欢
    • 2018-03-18
    • 2017-11-03
    • 2016-06-02
    • 2012-03-26
    • 2021-07-05
    • 2023-03-24
    • 2017-12-11
    • 2015-09-07
    • 1970-01-01
    相关资源
    最近更新 更多