read_write_attributes.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * @file read_write_attributes.cpp
  3. * @author Fangjun Kuang <csukuangfj dot at gmail dot com>
  4. * @date December 2017
  5. *
  6. * @brief It demonstrates how to read and write attributes inside the
  7. * root group.
  8. *
  9. * Currently, only the following datatypes can be used as attributes:
  10. * - cv::String
  11. * - int
  12. * - double
  13. * - cv::InputArray (n-d continuous multichannel arrays)
  14. *
  15. * Although HDF supports associating attributes with both datasets and groups,
  16. * only support for the root group is implemented by OpenCV at present.
  17. */
  18. //! [tutorial]
  19. #include <iostream>
  20. #include <opencv2/core.hpp>
  21. #include <opencv2/hdf.hpp>
  22. using namespace cv;
  23. static void read_write_attributes()
  24. {
  25. String filename = "attributes.h5";
  26. //! [tutorial_open_file]
  27. Ptr<hdf::HDF5> h5io = hdf::open(filename);
  28. //! [tutorial_open_file]
  29. //! [tutorial_write_mat]
  30. String attr_mat_name = "array attribute";
  31. Mat attr_mat;
  32. attr_mat = (cv::Mat_<float>(2, 3) << 0, 1, 2, 3, 4, 5, 6);
  33. if (!h5io->atexists(attr_mat_name))
  34. h5io->atwrite(attr_mat, attr_mat_name);
  35. //! [tutorial_write_mat]
  36. //! [snippets_write_str]
  37. String attr_str_name = "string attribute";
  38. String attr_str = "Hello HDF5 from OpenCV!";
  39. if (!h5io->atexists(attr_str_name))
  40. h5io->atwrite(attr_str, attr_str_name);
  41. //! [snippets_write_str]
  42. String attr_int_name = "int attribute";
  43. int attr_int = 123456;
  44. if (!h5io->atexists(attr_int_name))
  45. h5io->atwrite(attr_int, attr_int_name);
  46. String attr_double_name = "double attribute";
  47. double attr_double = 45678.123;
  48. if (!h5io->atexists(attr_double_name))
  49. h5io->atwrite(attr_double, attr_double_name);
  50. // read attributes
  51. Mat expected_attr_mat;
  52. int expected_attr_int;
  53. double expected_attr_double;
  54. //! [snippets_read_str]
  55. String expected_attr_str;
  56. h5io->atread(&expected_attr_str, attr_str_name);
  57. //! [snippets_read_str]
  58. //! [tutorial_read_mat]
  59. h5io->atread(expected_attr_mat, attr_mat_name);
  60. //! [tutorial_read_mat]
  61. h5io->atread(&expected_attr_int, attr_int_name);
  62. h5io->atread(&expected_attr_double, attr_double_name);
  63. // check results
  64. CV_Assert(norm(attr_mat - expected_attr_mat) < 1e-10);
  65. CV_Assert(attr_str.compare(expected_attr_str) == 0);
  66. CV_Assert(attr_int == expected_attr_int);
  67. CV_Assert(fabs(attr_double - expected_attr_double) < 1e-10);
  68. //! [tutorial_close_file]
  69. h5io->close();
  70. //! [tutorial_close_file]
  71. }
  72. int main()
  73. {
  74. read_write_attributes();
  75. return 0;
  76. }
  77. //! [tutorial]