OpenCV  4.5.1
Open Source Computer Vision
Creating Groups

Goal

This tutorial will show you:

Source Code

The following code creates two groups: Group1 and SubGroup1, where SubGroup1 is a child of Group1.

You can download the code from here or find it in the file modules/hdf/samples/create_groups.cpp of the opencv_contrib source code library.

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/hdf.hpp>
using namespace cv;
int main()
{
Ptr<hdf::HDF5> h5io = hdf::open("mytest.h5");
// "/" means the root group, which is always present
if (!h5io->hlexists("/Group1"))
h5io->grcreate("/Group1");
else
std::cout << "/Group1 has already been created, skip it.\n";
// Note that Group1 has been created above, otherwise exception will occur
if (!h5io->hlexists("/Group1/SubGroup1"))
h5io->grcreate("/Group1/SubGroup1");
else
std::cout << "/Group1/SubGroup1 has already been created, skip it.\n";
h5io->close();
return 0;
}

Explanation

First, we create a HDF5 file

Ptr<hdf::HDF5> h5io = hdf::open("mytest.h5");

If the given file does not exist, it will be created. Otherwise, it is open for read and write.

Next, we create the group Group1

// "/" means the root group, which is always present
if (!h5io->hlexists("/Group1"))
h5io->grcreate("/Group1");
else
std::cout << "/Group1 has already been created, skip it.\n";

Note that we have to check whether /Group1 exists or not using the function cv::hdf::HDF5::hlexists() before creating it. You can not create a group with an existing name. Otherwise, an error will occur.

Then, we create the subgroup named Subgroup1. In order to indicate that it is a sub group of Group1, we have to use the group name /Group1/SubGroup1:

// Note that Group1 has been created above, otherwise exception will occur
if (!h5io->hlexists("/Group1/SubGroup1"))
h5io->grcreate("/Group1/SubGroup1");
else
std::cout << "/Group1/SubGroup1 has already been created, skip it.\n";

Note that before creating a subgroup, we have to make sure that its parent group exists. Otherwise, an error will occur.

In the end, we have to close the file

h5io->close();

Result

There are many tools that can be used to inspect a given HDF file, such as HDFView and h5dump. If you are using Ubuntu, you can install them with the following commands:

sudo apt-get install hdf5-tools hdfview

There are also binaries available from the The HDF Group official website https://support.hdfgroup.org/HDF5/Tutor/tools.html.

The following figure shows the result visualized with the tool HDFView:

create_groups.png
Figure 1: Results of creating groups and subgroups

The output for h5dump is:

$ h5dump mytest.h5
HDF5 "mytest.h5" {
GROUP "/" {
GROUP "Group1" {
GROUP "SubGroup1" {
}
}
}
}