OpenCV 5.0.0
Open Source Computer Vision
読み込み中...
検索中...
見つかりません
🤖 AIによる機械翻訳(非公式) — これは OpenCV 5.0.0 公式リファレンス(英語)を AI (Claude) で自動翻訳したものです。訳に誤りを含む場合があります。正確な情報は 公式英語版(原文) を参照してください。
属性の読み書き

目的

このチュートリアルでは次の内容を示す:

  • 属性の書き込み方
  • 属性の読み込み方
覚え書き
属性はグループやデータセットに関連付けることができるが、OpenCVではルートグループに対する属性のみが実装されている。サポートされている属性の型は int, double, cv::String および cv::InputArray(連続配列の場合のみ)である。

ソースコード

以下のコードは、 cv::Matcv::Stringintdouble のデータ型を持つ属性を、ルートグループ内で読み書きする方法を示す。

コードは こちら からダウンロードできる。または opencv_contrib のソースコードライブラリ内のファイル modules/hdf/samples/read_write_attributes.cpp にある。

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/hdf.hpp>
using namespace cv;
static void read_write_attributes()
{
String filename = "attributes.h5";
Ptr<hdf::HDF5> h5io = hdf::open(filename);
String attr_mat_name = "array attribute";
Mat attr_mat;
attr_mat = (cv::Mat_<float>(2, 3) << 0, 1, 2, 3, 4, 5, 6);
if (!h5io->atexists(attr_mat_name))
h5io->atwrite(attr_mat, attr_mat_name);
String attr_str_name = "string attribute";
String attr_str = "Hello HDF5 from OpenCV!";
if (!h5io->atexists(attr_str_name))
h5io->atwrite(attr_str, attr_str_name);
String attr_int_name = "int attribute";
int attr_int = 123456;
if (!h5io->atexists(attr_int_name))
h5io->atwrite(attr_int, attr_int_name);
String attr_double_name = "double attribute";
double attr_double = 45678.123;
if (!h5io->atexists(attr_double_name))
h5io->atwrite(attr_double, attr_double_name);
// read attributes
Mat expected_attr_mat;
int expected_attr_int;
double expected_attr_double;
String expected_attr_str;
h5io->atread(&expected_attr_str, attr_str_name);
h5io->atread(expected_attr_mat, attr_mat_name);
h5io->atread(&expected_attr_int, attr_int_name);
h5io->atread(&expected_attr_double, attr_double_name);
// check results
CV_Assert(norm(attr_mat - expected_attr_mat) < 1e-10);
CV_Assert(attr_str.compare(expected_attr_str) == 0);
CV_Assert(attr_int == expected_attr_int);
CV_Assert(fabs(attr_double - expected_attr_double) < 1e-10);
h5io->close();
}
int main()
{
read_write_attributes();
return 0;
}

説明

最初のステップはHDF5ファイルを開くことである:

Ptr<hdf::HDF5> h5io = hdf::open(filename);

次に cv::hdf::HDF5::atwrite() を使い、値と名前を指定して属性を書き込む:

String attr_mat_name = "array attribute";
Mat attr_mat;
attr_mat = (cv::Mat_<float>(2, 3) << 0, 1, 2, 3, 4, 5, 6);
if (!h5io->atexists(attr_mat_name))
h5io->atwrite(attr_mat, attr_mat_name);
警告
属性を書き込む前に、cv::hdf::HDF5::atexists() を使ってその属性が存在しないことを確認する必要がある。

属性を読み込むには、属性名を指定して cv::hdf::HDF5::atread() を使う

h5io->atread(expected_attr_mat, attr_mat_name);

最後に、HDFファイルを閉じる必要がある

h5io->close();

結果

図1と図2は、ツールHDFViewを使って可視化した結果を示している。

Figure 1: Attributes of the root group
Figure 2: Detailed attribute information