persistence.hpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  15. // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  16. // Third party copyrights are property of their respective owners.
  17. //
  18. // Redistribution and use in source and binary forms, with or without modification,
  19. // are permitted provided that the following conditions are met:
  20. //
  21. // * Redistribution's of source code must retain the above copyright notice,
  22. // this list of conditions and the following disclaimer.
  23. //
  24. // * Redistribution's in binary form must reproduce the above copyright notice,
  25. // this list of conditions and the following disclaimer in the documentation
  26. // and/or other materials provided with the distribution.
  27. //
  28. // * The name of the copyright holders may not be used to endorse or promote products
  29. // derived from this software without specific prior written permission.
  30. //
  31. // This software is provided by the copyright holders and contributors "as is" and
  32. // any express or implied warranties, including, but not limited to, the implied
  33. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  34. // In no event shall the Intel Corporation or contributors be liable for any direct,
  35. // indirect, incidental, special, exemplary, or consequential damages
  36. // (including, but not limited to, procurement of substitute goods or services;
  37. // loss of use, data, or profits; or business interruption) however caused
  38. // and on any theory of liability, whether in contract, strict liability,
  39. // or tort (including negligence or otherwise) arising in any way out of
  40. // the use of this software, even if advised of the possibility of such damage.
  41. //
  42. //M*/
  43. #ifndef OPENCV_CORE_PERSISTENCE_HPP
  44. #define OPENCV_CORE_PERSISTENCE_HPP
  45. #ifndef CV_DOXYGEN
  46. /// Define to support persistence legacy formats
  47. #define CV__LEGACY_PERSISTENCE
  48. #endif
  49. #ifndef __cplusplus
  50. # error persistence.hpp header must be compiled as C++
  51. #endif
  52. //! @addtogroup core_c
  53. //! @{
  54. /** @brief "black box" representation of the file storage associated with a file on disk.
  55. Several functions that are described below take CvFileStorage\* as inputs and allow the user to
  56. save or to load hierarchical collections that consist of scalar values, standard CXCore objects
  57. (such as matrices, sequences, graphs), and user-defined objects.
  58. OpenCV can read and write data in XML (<http://www.w3c.org/XML>), YAML (<http://www.yaml.org>) or
  59. JSON (<http://www.json.org/>) formats. Below is an example of 3x3 floating-point identity matrix A,
  60. stored in XML and YAML files
  61. using CXCore functions:
  62. XML:
  63. @code{.xml}
  64. <?xml version="1.0">
  65. <opencv_storage>
  66. <A type_id="opencv-matrix">
  67. <rows>3</rows>
  68. <cols>3</cols>
  69. <dt>f</dt>
  70. <data>1. 0. 0. 0. 1. 0. 0. 0. 1.</data>
  71. </A>
  72. </opencv_storage>
  73. @endcode
  74. YAML:
  75. @code{.yaml}
  76. %YAML:1.0
  77. A: !!opencv-matrix
  78. rows: 3
  79. cols: 3
  80. dt: f
  81. data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1.]
  82. @endcode
  83. As it can be seen from the examples, XML uses nested tags to represent hierarchy, while YAML uses
  84. indentation for that purpose (similar to the Python programming language).
  85. The same functions can read and write data in both formats; the particular format is determined by
  86. the extension of the opened file, ".xml" for XML files, ".yml" or ".yaml" for YAML and ".json" for
  87. JSON.
  88. */
  89. typedef struct CvFileStorage CvFileStorage;
  90. typedef struct CvFileNode CvFileNode;
  91. typedef struct CvMat CvMat;
  92. typedef struct CvMatND CvMatND;
  93. //! @} core_c
  94. #include "opencv2/core/types.hpp"
  95. #include "opencv2/core/mat.hpp"
  96. namespace cv {
  97. /** @addtogroup core_xml
  98. XML/YAML/JSON file storages. {#xml_storage}
  99. =======================
  100. Writing to a file storage.
  101. --------------------------
  102. You can store and then restore various OpenCV data structures to/from XML (<http://www.w3c.org/XML>),
  103. YAML (<http://www.yaml.org>) or JSON (<http://www.json.org/>) formats. Also, it is possible to store
  104. and load arbitrarily complex data structures, which include OpenCV data structures, as well as
  105. primitive data types (integer and floating-point numbers and text strings) as their elements.
  106. Use the following procedure to write something to XML, YAML or JSON:
  107. -# Create new FileStorage and open it for writing. It can be done with a single call to
  108. FileStorage::FileStorage constructor that takes a filename, or you can use the default constructor
  109. and then call FileStorage::open. Format of the file (XML, YAML or JSON) is determined from the filename
  110. extension (".xml", ".yml"/".yaml" and ".json", respectively)
  111. -# Write all the data you want using the streaming operator `<<`, just like in the case of STL
  112. streams.
  113. -# Close the file using FileStorage::release. FileStorage destructor also closes the file.
  114. Here is an example:
  115. @code
  116. #include "opencv2/opencv.hpp"
  117. #include <time.h>
  118. using namespace cv;
  119. int main(int, char** argv)
  120. {
  121. FileStorage fs("test.yml", FileStorage::WRITE);
  122. fs << "frameCount" << 5;
  123. time_t rawtime; time(&rawtime);
  124. fs << "calibrationDate" << asctime(localtime(&rawtime));
  125. Mat cameraMatrix = (Mat_<double>(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1);
  126. Mat distCoeffs = (Mat_<double>(5,1) << 0.1, 0.01, -0.001, 0, 0);
  127. fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs;
  128. fs << "features" << "[";
  129. for( int i = 0; i < 3; i++ )
  130. {
  131. int x = rand() % 640;
  132. int y = rand() % 480;
  133. uchar lbp = rand() % 256;
  134. fs << "{:" << "x" << x << "y" << y << "lbp" << "[:";
  135. for( int j = 0; j < 8; j++ )
  136. fs << ((lbp >> j) & 1);
  137. fs << "]" << "}";
  138. }
  139. fs << "]";
  140. fs.release();
  141. return 0;
  142. }
  143. @endcode
  144. The sample above stores to YML an integer, a text string (calibration date), 2 matrices, and a custom
  145. structure "feature", which includes feature coordinates and LBP (local binary pattern) value. Here
  146. is output of the sample:
  147. @code{.yaml}
  148. %YAML:1.0
  149. frameCount: 5
  150. calibrationDate: "Fri Jun 17 14:09:29 2011\n"
  151. cameraMatrix: !!opencv-matrix
  152. rows: 3
  153. cols: 3
  154. dt: d
  155. data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ]
  156. distCoeffs: !!opencv-matrix
  157. rows: 5
  158. cols: 1
  159. dt: d
  160. data: [ 1.0000000000000001e-01, 1.0000000000000000e-02,
  161. -1.0000000000000000e-03, 0., 0. ]
  162. features:
  163. - { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] }
  164. - { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] }
  165. - { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] }
  166. @endcode
  167. As an exercise, you can replace ".yml" with ".xml" or ".json" in the sample above and see, how the
  168. corresponding XML file will look like.
  169. Several things can be noted by looking at the sample code and the output:
  170. - The produced YAML (and XML/JSON) consists of heterogeneous collections that can be nested. There are
  171. 2 types of collections: named collections (mappings) and unnamed collections (sequences). In mappings
  172. each element has a name and is accessed by name. This is similar to structures and std::map in
  173. C/C++ and dictionaries in Python. In sequences elements do not have names, they are accessed by
  174. indices. This is similar to arrays and std::vector in C/C++ and lists, tuples in Python.
  175. "Heterogeneous" means that elements of each single collection can have different types.
  176. Top-level collection in YAML/XML/JSON is a mapping. Each matrix is stored as a mapping, and the matrix
  177. elements are stored as a sequence. Then, there is a sequence of features, where each feature is
  178. represented a mapping, and lbp value in a nested sequence.
  179. - When you write to a mapping (a structure), you write element name followed by its value. When you
  180. write to a sequence, you simply write the elements one by one. OpenCV data structures (such as
  181. cv::Mat) are written in absolutely the same way as simple C data structures - using `<<`
  182. operator.
  183. - To write a mapping, you first write the special string `{` to the storage, then write the
  184. elements as pairs (`fs << <element_name> << <element_value>`) and then write the closing
  185. `}`.
  186. - To write a sequence, you first write the special string `[`, then write the elements, then
  187. write the closing `]`.
  188. - In YAML/JSON (but not XML), mappings and sequences can be written in a compact Python-like inline
  189. form. In the sample above matrix elements, as well as each feature, including its lbp value, is
  190. stored in such inline form. To store a mapping/sequence in a compact form, put `:` after the
  191. opening character, e.g. use `{:` instead of `{` and `[:` instead of `[`. When the
  192. data is written to XML, those extra `:` are ignored.
  193. Reading data from a file storage.
  194. ---------------------------------
  195. To read the previously written XML, YAML or JSON file, do the following:
  196. -# Open the file storage using FileStorage::FileStorage constructor or FileStorage::open method.
  197. In the current implementation the whole file is parsed and the whole representation of file
  198. storage is built in memory as a hierarchy of file nodes (see FileNode)
  199. -# Read the data you are interested in. Use FileStorage::operator [], FileNode::operator []
  200. and/or FileNodeIterator.
  201. -# Close the storage using FileStorage::release.
  202. Here is how to read the file created by the code sample above:
  203. @code
  204. FileStorage fs2("test.yml", FileStorage::READ);
  205. // first method: use (type) operator on FileNode.
  206. int frameCount = (int)fs2["frameCount"];
  207. String date;
  208. // second method: use FileNode::operator >>
  209. fs2["calibrationDate"] >> date;
  210. Mat cameraMatrix2, distCoeffs2;
  211. fs2["cameraMatrix"] >> cameraMatrix2;
  212. fs2["distCoeffs"] >> distCoeffs2;
  213. cout << "frameCount: " << frameCount << endl
  214. << "calibration date: " << date << endl
  215. << "camera matrix: " << cameraMatrix2 << endl
  216. << "distortion coeffs: " << distCoeffs2 << endl;
  217. FileNode features = fs2["features"];
  218. FileNodeIterator it = features.begin(), it_end = features.end();
  219. int idx = 0;
  220. std::vector<uchar> lbpval;
  221. // iterate through a sequence using FileNodeIterator
  222. for( ; it != it_end; ++it, idx++ )
  223. {
  224. cout << "feature #" << idx << ": ";
  225. cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: (";
  226. // you can also easily read numerical arrays using FileNode >> std::vector operator.
  227. (*it)["lbp"] >> lbpval;
  228. for( int i = 0; i < (int)lbpval.size(); i++ )
  229. cout << " " << (int)lbpval[i];
  230. cout << ")" << endl;
  231. }
  232. fs2.release();
  233. @endcode
  234. Format specification {#format_spec}
  235. --------------------
  236. `([count]{u|c|w|s|i|f|d})`... where the characters correspond to fundamental C++ types:
  237. - `u` 8-bit unsigned number
  238. - `c` 8-bit signed number
  239. - `w` 16-bit unsigned number
  240. - `s` 16-bit signed number
  241. - `i` 32-bit signed number
  242. - `f` single precision floating-point number
  243. - `d` double precision floating-point number
  244. - `r` pointer, 32 lower bits of which are written as a signed integer. The type can be used to
  245. store structures with links between the elements.
  246. `count` is the optional counter of values of a given type. For example, `2if` means that each array
  247. element is a structure of 2 integers, followed by a single-precision floating-point number. The
  248. equivalent notations of the above specification are `iif`, `2i1f` and so forth. Other examples: `u`
  249. means that the array consists of bytes, and `2d` means the array consists of pairs of doubles.
  250. @see @ref samples/cpp/filestorage.cpp
  251. */
  252. //! @{
  253. /** @example samples/cpp/filestorage.cpp
  254. A complete example using the FileStorage interface
  255. */
  256. ////////////////////////// XML & YAML I/O //////////////////////////
  257. class CV_EXPORTS FileNode;
  258. class CV_EXPORTS FileNodeIterator;
  259. /** @brief XML/YAML/JSON file storage class that encapsulates all the information necessary for writing or
  260. reading data to/from a file.
  261. */
  262. class CV_EXPORTS_W FileStorage
  263. {
  264. public:
  265. //! file storage mode
  266. enum Mode
  267. {
  268. READ = 0, //!< value, open the file for reading
  269. WRITE = 1, //!< value, open the file for writing
  270. APPEND = 2, //!< value, open the file for appending
  271. MEMORY = 4, //!< flag, read data from source or write data to the internal buffer (which is
  272. //!< returned by FileStorage::release)
  273. FORMAT_MASK = (7<<3), //!< mask for format flags
  274. FORMAT_AUTO = 0, //!< flag, auto format
  275. FORMAT_XML = (1<<3), //!< flag, XML format
  276. FORMAT_YAML = (2<<3), //!< flag, YAML format
  277. FORMAT_JSON = (3<<3), //!< flag, JSON format
  278. BASE64 = 64, //!< flag, write rawdata in Base64 by default. (consider using WRITE_BASE64)
  279. WRITE_BASE64 = BASE64 | WRITE, //!< flag, enable both WRITE and BASE64
  280. };
  281. enum
  282. {
  283. UNDEFINED = 0,
  284. VALUE_EXPECTED = 1,
  285. NAME_EXPECTED = 2,
  286. INSIDE_MAP = 4
  287. };
  288. /** @brief The constructors.
  289. The full constructor opens the file. Alternatively you can use the default constructor and then
  290. call FileStorage::open.
  291. */
  292. CV_WRAP FileStorage();
  293. /** @overload
  294. @copydoc open()
  295. */
  296. CV_WRAP FileStorage(const String& filename, int flags, const String& encoding=String());
  297. /** @overload */
  298. FileStorage(CvFileStorage* fs, bool owning=true);
  299. //! the destructor. calls release()
  300. virtual ~FileStorage();
  301. /** @brief Opens a file.
  302. See description of parameters in FileStorage::FileStorage. The method calls FileStorage::release
  303. before opening the file.
  304. @param filename Name of the file to open or the text string to read the data from.
  305. Extension of the file (.xml, .yml/.yaml or .json) determines its format (XML, YAML or JSON
  306. respectively). Also you can append .gz to work with compressed files, for example myHugeMatrix.xml.gz. If both
  307. FileStorage::WRITE and FileStorage::MEMORY flags are specified, source is used just to specify
  308. the output file format (e.g. mydata.xml, .yml etc.). A file name can also contain parameters.
  309. You can use this format, "*?base64" (e.g. "file.json?base64" (case sensitive)), as an alternative to
  310. FileStorage::BASE64 flag.
  311. @param flags Mode of operation. One of FileStorage::Mode
  312. @param encoding Encoding of the file. Note that UTF-16 XML encoding is not supported currently and
  313. you should use 8-bit encoding instead of it.
  314. */
  315. CV_WRAP virtual bool open(const String& filename, int flags, const String& encoding=String());
  316. /** @brief Checks whether the file is opened.
  317. @returns true if the object is associated with the current file and false otherwise. It is a
  318. good practice to call this method after you tried to open a file.
  319. */
  320. CV_WRAP virtual bool isOpened() const;
  321. /** @brief Closes the file and releases all the memory buffers.
  322. Call this method after all I/O operations with the storage are finished.
  323. */
  324. CV_WRAP virtual void release();
  325. /** @brief Closes the file and releases all the memory buffers.
  326. Call this method after all I/O operations with the storage are finished. If the storage was
  327. opened for writing data and FileStorage::WRITE was specified
  328. */
  329. CV_WRAP virtual String releaseAndGetString();
  330. /** @brief Returns the first element of the top-level mapping.
  331. @returns The first element of the top-level mapping.
  332. */
  333. CV_WRAP FileNode getFirstTopLevelNode() const;
  334. /** @brief Returns the top-level mapping
  335. @param streamidx Zero-based index of the stream. In most cases there is only one stream in the file.
  336. However, YAML supports multiple streams and so there can be several.
  337. @returns The top-level mapping.
  338. */
  339. CV_WRAP FileNode root(int streamidx=0) const;
  340. /** @brief Returns the specified element of the top-level mapping.
  341. @param nodename Name of the file node.
  342. @returns Node with the given name.
  343. */
  344. FileNode operator[](const String& nodename) const;
  345. /** @overload */
  346. CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const;
  347. /** @brief Returns the obsolete C FileStorage structure.
  348. @returns Pointer to the underlying C FileStorage structure
  349. */
  350. CvFileStorage* operator *() { return fs.get(); }
  351. /** @overload */
  352. const CvFileStorage* operator *() const { return fs.get(); }
  353. /** @brief Writes multiple numbers.
  354. Writes one or more numbers of the specified format to the currently written structure. Usually it is
  355. more convenient to use operator `<<` instead of this method.
  356. @param fmt Specification of each array element, see @ref format_spec "format specification"
  357. @param vec Pointer to the written array.
  358. @param len Number of the uchar elements to write.
  359. */
  360. void writeRaw( const String& fmt, const uchar* vec, size_t len );
  361. /** @brief Writes the registered C structure (CvMat, CvMatND, CvSeq).
  362. @param name Name of the written object.
  363. @param obj Pointer to the object.
  364. @see cvWrite for details.
  365. */
  366. void writeObj( const String& name, const void* obj );
  367. /**
  368. * @brief Simplified writing API to use with bindings.
  369. * @param name Name of the written object
  370. * @param val Value of the written object
  371. */
  372. CV_WRAP void write(const String& name, int val);
  373. /// @overload
  374. CV_WRAP void write(const String& name, double val);
  375. /// @overload
  376. CV_WRAP void write(const String& name, const String& val);
  377. /// @overload
  378. CV_WRAP void write(const String& name, InputArray val);
  379. /** @brief Writes a comment.
  380. The function writes a comment into file storage. The comments are skipped when the storage is read.
  381. @param comment The written comment, single-line or multi-line
  382. @param append If true, the function tries to put the comment at the end of current line.
  383. Else if the comment is multi-line, or if it does not fit at the end of the current
  384. line, the comment starts a new line.
  385. */
  386. CV_WRAP void writeComment(const String& comment, bool append = false);
  387. /** @brief Starts to write a nested structure (sequence or a mapping).
  388. @param name name of the structure (if it's a member of parent mapping, otherwise it should be empty
  389. @param flags type of the structure (FileNode::MAP or FileNode::SEQ (both with optional FileNode::FLOW)).
  390. @param typeName usually an empty string
  391. */
  392. CV_WRAP void startWriteStruct(const String& name, int flags, const String& typeName=String());
  393. /** @brief Finishes writing nested structure (should pair startWriteStruct())
  394. */
  395. CV_WRAP void endWriteStruct();
  396. /** @brief Returns the normalized object name for the specified name of a file.
  397. @param filename Name of a file
  398. @returns The normalized object name.
  399. */
  400. static String getDefaultObjectName(const String& filename);
  401. /** @brief Returns the current format.
  402. * @returns The current format, see FileStorage::Mode
  403. */
  404. CV_WRAP int getFormat() const;
  405. Ptr<CvFileStorage> fs; //!< the underlying C FileStorage structure
  406. String elname; //!< the currently written element
  407. std::vector<char> structs; //!< the stack of written structures
  408. int state; //!< the writer state
  409. };
  410. template<> CV_EXPORTS void DefaultDeleter<CvFileStorage>::operator ()(CvFileStorage* obj) const;
  411. /** @brief File Storage Node class.
  412. The node is used to store each and every element of the file storage opened for reading. When
  413. XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of
  414. nodes. Each node can be a "leaf" that is contain a single number or a string, or be a collection of
  415. other nodes. There can be named collections (mappings) where each element has a name and it is
  416. accessed by a name, and ordered collections (sequences) where elements do not have names but rather
  417. accessed by index. Type of the file node can be determined using FileNode::type method.
  418. Note that file nodes are only used for navigating file storages opened for reading. When a file
  419. storage is opened for writing, no data is stored in memory after it is written.
  420. */
  421. class CV_EXPORTS_W_SIMPLE FileNode
  422. {
  423. public:
  424. //! type of the file storage node
  425. enum Type
  426. {
  427. NONE = 0, //!< empty node
  428. INT = 1, //!< an integer
  429. REAL = 2, //!< floating-point number
  430. FLOAT = REAL, //!< synonym or REAL
  431. STR = 3, //!< text string in UTF-8 encoding
  432. STRING = STR, //!< synonym for STR
  433. REF = 4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others
  434. SEQ = 5, //!< sequence
  435. MAP = 6, //!< mapping
  436. TYPE_MASK = 7,
  437. FLOW = 8, //!< compact representation of a sequence or mapping. Used only by YAML writer
  438. USER = 16, //!< a registered object (e.g. a matrix)
  439. EMPTY = 32, //!< empty structure (sequence or mapping)
  440. NAMED = 64 //!< the node has a name (i.e. it is element of a mapping)
  441. };
  442. /** @brief The constructors.
  443. These constructors are used to create a default file node, construct it from obsolete structures or
  444. from the another file node.
  445. */
  446. CV_WRAP FileNode();
  447. /** @overload
  448. @param fs Pointer to the obsolete file storage structure.
  449. @param node File node to be used as initialization for the created file node.
  450. */
  451. FileNode(const CvFileStorage* fs, const CvFileNode* node);
  452. /** @overload
  453. @param node File node to be used as initialization for the created file node.
  454. */
  455. FileNode(const FileNode& node);
  456. FileNode& operator=(const FileNode& node);
  457. /** @brief Returns element of a mapping node or a sequence node.
  458. @param nodename Name of an element in the mapping node.
  459. @returns Returns the element with the given identifier.
  460. */
  461. FileNode operator[](const String& nodename) const;
  462. /** @overload
  463. @param nodename Name of an element in the mapping node.
  464. */
  465. CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const;
  466. /** @overload
  467. @param i Index of an element in the sequence node.
  468. */
  469. CV_WRAP_AS(at) FileNode operator[](int i) const;
  470. /** @brief Returns keys of a mapping node.
  471. @returns Keys of a mapping node.
  472. */
  473. CV_WRAP std::vector<String> keys() const;
  474. /** @brief Returns type of the node.
  475. @returns Type of the node. See FileNode::Type
  476. */
  477. CV_WRAP int type() const;
  478. //! returns true if the node is empty
  479. CV_WRAP bool empty() const;
  480. //! returns true if the node is a "none" object
  481. CV_WRAP bool isNone() const;
  482. //! returns true if the node is a sequence
  483. CV_WRAP bool isSeq() const;
  484. //! returns true if the node is a mapping
  485. CV_WRAP bool isMap() const;
  486. //! returns true if the node is an integer
  487. CV_WRAP bool isInt() const;
  488. //! returns true if the node is a floating-point number
  489. CV_WRAP bool isReal() const;
  490. //! returns true if the node is a text string
  491. CV_WRAP bool isString() const;
  492. //! returns true if the node has a name
  493. CV_WRAP bool isNamed() const;
  494. //! returns the node name or an empty string if the node is nameless
  495. CV_WRAP String name() const;
  496. //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise.
  497. CV_WRAP size_t size() const;
  498. //! returns the node content as an integer. If the node stores floating-point number, it is rounded.
  499. operator int() const;
  500. //! returns the node content as float
  501. operator float() const;
  502. //! returns the node content as double
  503. operator double() const;
  504. //! returns the node content as text string
  505. operator String() const;
  506. operator std::string() const;
  507. //! returns pointer to the underlying file node
  508. CvFileNode* operator *();
  509. //! returns pointer to the underlying file node
  510. const CvFileNode* operator* () const;
  511. //! returns iterator pointing to the first node element
  512. FileNodeIterator begin() const;
  513. //! returns iterator pointing to the element following the last node element
  514. FileNodeIterator end() const;
  515. /** @brief Reads node elements to the buffer with the specified format.
  516. Usually it is more convenient to use operator `>>` instead of this method.
  517. @param fmt Specification of each array element. See @ref format_spec "format specification"
  518. @param vec Pointer to the destination array.
  519. @param len Number of bytes to read (buffer size limit). If it is greater than number of
  520. remaining elements then all of them will be read.
  521. */
  522. void readRaw( const String& fmt, uchar* vec, size_t len ) const;
  523. //! reads the registered object and returns pointer to it
  524. void* readObj() const;
  525. //! Simplified reading API to use with bindings.
  526. CV_WRAP double real() const;
  527. //! Simplified reading API to use with bindings.
  528. CV_WRAP String string() const;
  529. //! Simplified reading API to use with bindings.
  530. CV_WRAP Mat mat() const;
  531. // do not use wrapper pointer classes for better efficiency
  532. const CvFileStorage* fs;
  533. const CvFileNode* node;
  534. };
  535. /** @brief used to iterate through sequences and mappings.
  536. A standard STL notation, with node.begin(), node.end() denoting the beginning and the end of a
  537. sequence, stored in node. See the data reading sample in the beginning of the section.
  538. */
  539. class CV_EXPORTS FileNodeIterator
  540. {
  541. public:
  542. /** @brief The constructors.
  543. These constructors are used to create a default iterator, set it to specific element in a file node
  544. or construct it from another iterator.
  545. */
  546. FileNodeIterator();
  547. /** @overload
  548. @param fs File storage for the iterator.
  549. @param node File node for the iterator.
  550. @param ofs Index of the element in the node. The created iterator will point to this element.
  551. */
  552. FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0);
  553. /** @overload
  554. @param it Iterator to be used as initialization for the created iterator.
  555. */
  556. FileNodeIterator(const FileNodeIterator& it);
  557. FileNodeIterator& operator=(const FileNodeIterator& it);
  558. //! returns the currently observed element
  559. FileNode operator *() const;
  560. //! accesses the currently observed element methods
  561. FileNode operator ->() const;
  562. //! moves iterator to the next node
  563. FileNodeIterator& operator ++ ();
  564. //! moves iterator to the next node
  565. FileNodeIterator operator ++ (int);
  566. //! moves iterator to the previous node
  567. FileNodeIterator& operator -- ();
  568. //! moves iterator to the previous node
  569. FileNodeIterator operator -- (int);
  570. //! moves iterator forward by the specified offset (possibly negative)
  571. FileNodeIterator& operator += (int ofs);
  572. //! moves iterator backward by the specified offset (possibly negative)
  573. FileNodeIterator& operator -= (int ofs);
  574. /** @brief Reads node elements to the buffer with the specified format.
  575. Usually it is more convenient to use operator `>>` instead of this method.
  576. @param fmt Specification of each array element. See @ref format_spec "format specification"
  577. @param vec Pointer to the destination array.
  578. @param len Number of bytes to read (buffer size limit). If it is greater than number of
  579. remaining elements then all of them will be read.
  580. */
  581. FileNodeIterator& readRaw( const String& fmt, uchar* vec,
  582. size_t len=(size_t)INT_MAX );
  583. struct SeqReader
  584. {
  585. int header_size;
  586. void* seq; /* sequence, beign read; CvSeq */
  587. void* block; /* current block; CvSeqBlock */
  588. schar* ptr; /* pointer to element be read next */
  589. schar* block_min; /* pointer to the beginning of block */
  590. schar* block_max; /* pointer to the end of block */
  591. int delta_index;/* = seq->first->start_index */
  592. schar* prev_elem; /* pointer to previous element */
  593. };
  594. const CvFileStorage* fs;
  595. const CvFileNode* container;
  596. SeqReader reader;
  597. size_t remaining;
  598. };
  599. //! @} core_xml
  600. /////////////////// XML & YAML I/O implementation //////////////////
  601. //! @relates cv::FileStorage
  602. //! @{
  603. CV_EXPORTS void write( FileStorage& fs, const String& name, int value );
  604. CV_EXPORTS void write( FileStorage& fs, const String& name, float value );
  605. CV_EXPORTS void write( FileStorage& fs, const String& name, double value );
  606. CV_EXPORTS void write( FileStorage& fs, const String& name, const String& value );
  607. CV_EXPORTS void write( FileStorage& fs, const String& name, const Mat& value );
  608. CV_EXPORTS void write( FileStorage& fs, const String& name, const SparseMat& value );
  609. #ifdef CV__LEGACY_PERSISTENCE
  610. CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector<KeyPoint>& value);
  611. CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector<DMatch>& value);
  612. #endif
  613. CV_EXPORTS void writeScalar( FileStorage& fs, int value );
  614. CV_EXPORTS void writeScalar( FileStorage& fs, float value );
  615. CV_EXPORTS void writeScalar( FileStorage& fs, double value );
  616. CV_EXPORTS void writeScalar( FileStorage& fs, const String& value );
  617. //! @}
  618. //! @relates cv::FileNode
  619. //! @{
  620. CV_EXPORTS void read(const FileNode& node, int& value, int default_value);
  621. CV_EXPORTS void read(const FileNode& node, float& value, float default_value);
  622. CV_EXPORTS void read(const FileNode& node, double& value, double default_value);
  623. CV_EXPORTS void read(const FileNode& node, String& value, const String& default_value);
  624. CV_EXPORTS void read(const FileNode& node, std::string& value, const std::string& default_value);
  625. CV_EXPORTS void read(const FileNode& node, Mat& mat, const Mat& default_mat = Mat() );
  626. CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat = SparseMat() );
  627. #ifdef CV__LEGACY_PERSISTENCE
  628. CV_EXPORTS void read(const FileNode& node, std::vector<KeyPoint>& keypoints);
  629. CV_EXPORTS void read(const FileNode& node, std::vector<DMatch>& matches);
  630. #endif
  631. CV_EXPORTS void read(const FileNode& node, KeyPoint& value, const KeyPoint& default_value);
  632. CV_EXPORTS void read(const FileNode& node, DMatch& value, const DMatch& default_value);
  633. template<typename _Tp> static inline void read(const FileNode& node, Point_<_Tp>& value, const Point_<_Tp>& default_value)
  634. {
  635. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  636. value = temp.size() != 2 ? default_value : Point_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]));
  637. }
  638. template<typename _Tp> static inline void read(const FileNode& node, Point3_<_Tp>& value, const Point3_<_Tp>& default_value)
  639. {
  640. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  641. value = temp.size() != 3 ? default_value : Point3_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]),
  642. saturate_cast<_Tp>(temp[2]));
  643. }
  644. template<typename _Tp> static inline void read(const FileNode& node, Size_<_Tp>& value, const Size_<_Tp>& default_value)
  645. {
  646. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  647. value = temp.size() != 2 ? default_value : Size_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]));
  648. }
  649. template<typename _Tp> static inline void read(const FileNode& node, Complex<_Tp>& value, const Complex<_Tp>& default_value)
  650. {
  651. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  652. value = temp.size() != 2 ? default_value : Complex<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]));
  653. }
  654. template<typename _Tp> static inline void read(const FileNode& node, Rect_<_Tp>& value, const Rect_<_Tp>& default_value)
  655. {
  656. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  657. value = temp.size() != 4 ? default_value : Rect_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]),
  658. saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3]));
  659. }
  660. template<typename _Tp, int cn> static inline void read(const FileNode& node, Vec<_Tp, cn>& value, const Vec<_Tp, cn>& default_value)
  661. {
  662. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  663. value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]);
  664. }
  665. template<typename _Tp> static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value)
  666. {
  667. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  668. value = temp.size() != 4 ? default_value : Scalar_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]),
  669. saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3]));
  670. }
  671. static inline void read(const FileNode& node, Range& value, const Range& default_value)
  672. {
  673. Point2i temp(value.start, value.end); const Point2i default_temp = Point2i(default_value.start, default_value.end);
  674. read(node, temp, default_temp);
  675. value.start = temp.x; value.end = temp.y;
  676. }
  677. //! @}
  678. /** @brief Writes string to a file storage.
  679. @relates cv::FileStorage
  680. */
  681. CV_EXPORTS FileStorage& operator << (FileStorage& fs, const String& str);
  682. //! @cond IGNORED
  683. namespace internal
  684. {
  685. class CV_EXPORTS WriteStructContext
  686. {
  687. public:
  688. WriteStructContext(FileStorage& _fs, const String& name, int flags, const String& typeName = String());
  689. ~WriteStructContext();
  690. private:
  691. FileStorage* fs;
  692. };
  693. template<typename _Tp, int numflag> class VecWriterProxy
  694. {
  695. public:
  696. VecWriterProxy( FileStorage* _fs ) : fs(_fs) {}
  697. void operator()(const std::vector<_Tp>& vec) const
  698. {
  699. size_t count = vec.size();
  700. for (size_t i = 0; i < count; i++)
  701. write(*fs, vec[i]);
  702. }
  703. private:
  704. FileStorage* fs;
  705. };
  706. template<typename _Tp> class VecWriterProxy<_Tp, 1>
  707. {
  708. public:
  709. VecWriterProxy( FileStorage* _fs ) : fs(_fs) {}
  710. void operator()(const std::vector<_Tp>& vec) const
  711. {
  712. int _fmt = traits::SafeFmt<_Tp>::fmt;
  713. char fmt[] = { (char)((_fmt >> 8) + '1'), (char)_fmt, '\0' };
  714. fs->writeRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, vec.size() * sizeof(_Tp));
  715. }
  716. private:
  717. FileStorage* fs;
  718. };
  719. template<typename _Tp, int numflag> class VecReaderProxy
  720. {
  721. public:
  722. VecReaderProxy( FileNodeIterator* _it ) : it(_it) {}
  723. void operator()(std::vector<_Tp>& vec, size_t count) const
  724. {
  725. count = std::min(count, it->remaining);
  726. vec.resize(count);
  727. for (size_t i = 0; i < count; i++, ++(*it))
  728. read(**it, vec[i], _Tp());
  729. }
  730. private:
  731. FileNodeIterator* it;
  732. };
  733. template<typename _Tp> class VecReaderProxy<_Tp, 1>
  734. {
  735. public:
  736. VecReaderProxy( FileNodeIterator* _it ) : it(_it) {}
  737. void operator()(std::vector<_Tp>& vec, size_t count) const
  738. {
  739. size_t remaining = it->remaining;
  740. size_t cn = DataType<_Tp>::channels;
  741. int _fmt = traits::SafeFmt<_Tp>::fmt;
  742. CV_Assert((_fmt >> 8) < 9);
  743. char fmt[] = { (char)((_fmt >> 8)+'1'), (char)_fmt, '\0' };
  744. CV_Assert((remaining % cn) == 0);
  745. size_t remaining1 = remaining / cn;
  746. count = count < remaining1 ? count : remaining1;
  747. vec.resize(count);
  748. it->readRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp));
  749. }
  750. private:
  751. FileNodeIterator* it;
  752. };
  753. } // internal
  754. //! @endcond
  755. //! @relates cv::FileStorage
  756. //! @{
  757. template<typename _Tp> static inline
  758. void write(FileStorage& fs, const _Tp& value)
  759. {
  760. write(fs, String(), value);
  761. }
  762. template<> inline
  763. void write( FileStorage& fs, const int& value )
  764. {
  765. writeScalar(fs, value);
  766. }
  767. template<> inline
  768. void write( FileStorage& fs, const float& value )
  769. {
  770. writeScalar(fs, value);
  771. }
  772. template<> inline
  773. void write( FileStorage& fs, const double& value )
  774. {
  775. writeScalar(fs, value);
  776. }
  777. template<> inline
  778. void write( FileStorage& fs, const String& value )
  779. {
  780. writeScalar(fs, value);
  781. }
  782. template<typename _Tp> static inline
  783. void write(FileStorage& fs, const Point_<_Tp>& pt )
  784. {
  785. write(fs, pt.x);
  786. write(fs, pt.y);
  787. }
  788. template<typename _Tp> static inline
  789. void write(FileStorage& fs, const Point3_<_Tp>& pt )
  790. {
  791. write(fs, pt.x);
  792. write(fs, pt.y);
  793. write(fs, pt.z);
  794. }
  795. template<typename _Tp> static inline
  796. void write(FileStorage& fs, const Size_<_Tp>& sz )
  797. {
  798. write(fs, sz.width);
  799. write(fs, sz.height);
  800. }
  801. template<typename _Tp> static inline
  802. void write(FileStorage& fs, const Complex<_Tp>& c )
  803. {
  804. write(fs, c.re);
  805. write(fs, c.im);
  806. }
  807. template<typename _Tp> static inline
  808. void write(FileStorage& fs, const Rect_<_Tp>& r )
  809. {
  810. write(fs, r.x);
  811. write(fs, r.y);
  812. write(fs, r.width);
  813. write(fs, r.height);
  814. }
  815. template<typename _Tp, int cn> static inline
  816. void write(FileStorage& fs, const Vec<_Tp, cn>& v )
  817. {
  818. for(int i = 0; i < cn; i++)
  819. write(fs, v.val[i]);
  820. }
  821. template<typename _Tp> static inline
  822. void write(FileStorage& fs, const Scalar_<_Tp>& s )
  823. {
  824. write(fs, s.val[0]);
  825. write(fs, s.val[1]);
  826. write(fs, s.val[2]);
  827. write(fs, s.val[3]);
  828. }
  829. static inline
  830. void write(FileStorage& fs, const Range& r )
  831. {
  832. write(fs, r.start);
  833. write(fs, r.end);
  834. }
  835. template<typename _Tp> static inline
  836. void write( FileStorage& fs, const std::vector<_Tp>& vec )
  837. {
  838. cv::internal::VecWriterProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> w(&fs);
  839. w(vec);
  840. }
  841. template<typename _Tp> static inline
  842. void write(FileStorage& fs, const String& name, const Point_<_Tp>& pt )
  843. {
  844. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  845. write(fs, pt);
  846. }
  847. template<typename _Tp> static inline
  848. void write(FileStorage& fs, const String& name, const Point3_<_Tp>& pt )
  849. {
  850. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  851. write(fs, pt);
  852. }
  853. template<typename _Tp> static inline
  854. void write(FileStorage& fs, const String& name, const Size_<_Tp>& sz )
  855. {
  856. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  857. write(fs, sz);
  858. }
  859. template<typename _Tp> static inline
  860. void write(FileStorage& fs, const String& name, const Complex<_Tp>& c )
  861. {
  862. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  863. write(fs, c);
  864. }
  865. template<typename _Tp> static inline
  866. void write(FileStorage& fs, const String& name, const Rect_<_Tp>& r )
  867. {
  868. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  869. write(fs, r);
  870. }
  871. template<typename _Tp, int cn> static inline
  872. void write(FileStorage& fs, const String& name, const Vec<_Tp, cn>& v )
  873. {
  874. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  875. write(fs, v);
  876. }
  877. template<typename _Tp> static inline
  878. void write(FileStorage& fs, const String& name, const Scalar_<_Tp>& s )
  879. {
  880. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  881. write(fs, s);
  882. }
  883. static inline
  884. void write(FileStorage& fs, const String& name, const Range& r )
  885. {
  886. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  887. write(fs, r);
  888. }
  889. static inline
  890. void write(FileStorage& fs, const String& name, const KeyPoint& kpt)
  891. {
  892. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  893. write(fs, kpt.pt.x);
  894. write(fs, kpt.pt.y);
  895. write(fs, kpt.size);
  896. write(fs, kpt.angle);
  897. write(fs, kpt.response);
  898. write(fs, kpt.octave);
  899. write(fs, kpt.class_id);
  900. }
  901. static inline
  902. void write(FileStorage& fs, const String& name, const DMatch& m)
  903. {
  904. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  905. write(fs, m.queryIdx);
  906. write(fs, m.trainIdx);
  907. write(fs, m.imgIdx);
  908. write(fs, m.distance);
  909. }
  910. template<typename _Tp> static inline
  911. void write( FileStorage& fs, const String& name, const std::vector<_Tp>& vec )
  912. {
  913. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0));
  914. write(fs, vec);
  915. }
  916. template<typename _Tp> static inline
  917. void write( FileStorage& fs, const String& name, const std::vector< std::vector<_Tp> >& vec )
  918. {
  919. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ);
  920. for(size_t i = 0; i < vec.size(); i++)
  921. {
  922. cv::internal::WriteStructContext ws_(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0));
  923. write(fs, vec[i]);
  924. }
  925. }
  926. #ifdef CV__LEGACY_PERSISTENCE
  927. // This code is not needed anymore, but it is preserved here to keep source compatibility
  928. // Implementation is similar to templates instantiations
  929. static inline void write(FileStorage& fs, const KeyPoint& kpt) { write(fs, String(), kpt); }
  930. static inline void write(FileStorage& fs, const DMatch& m) { write(fs, String(), m); }
  931. static inline void write(FileStorage& fs, const std::vector<KeyPoint>& vec)
  932. {
  933. cv::internal::VecWriterProxy<KeyPoint, 0> w(&fs);
  934. w(vec);
  935. }
  936. static inline void write(FileStorage& fs, const std::vector<DMatch>& vec)
  937. {
  938. cv::internal::VecWriterProxy<DMatch, 0> w(&fs);
  939. w(vec);
  940. }
  941. #endif
  942. //! @} FileStorage
  943. //! @relates cv::FileNode
  944. //! @{
  945. static inline
  946. void read(const FileNode& node, bool& value, bool default_value)
  947. {
  948. int temp;
  949. read(node, temp, (int)default_value);
  950. value = temp != 0;
  951. }
  952. static inline
  953. void read(const FileNode& node, uchar& value, uchar default_value)
  954. {
  955. int temp;
  956. read(node, temp, (int)default_value);
  957. value = saturate_cast<uchar>(temp);
  958. }
  959. static inline
  960. void read(const FileNode& node, schar& value, schar default_value)
  961. {
  962. int temp;
  963. read(node, temp, (int)default_value);
  964. value = saturate_cast<schar>(temp);
  965. }
  966. static inline
  967. void read(const FileNode& node, ushort& value, ushort default_value)
  968. {
  969. int temp;
  970. read(node, temp, (int)default_value);
  971. value = saturate_cast<ushort>(temp);
  972. }
  973. static inline
  974. void read(const FileNode& node, short& value, short default_value)
  975. {
  976. int temp;
  977. read(node, temp, (int)default_value);
  978. value = saturate_cast<short>(temp);
  979. }
  980. template<typename _Tp> static inline
  981. void read( FileNodeIterator& it, std::vector<_Tp>& vec, size_t maxCount = (size_t)INT_MAX )
  982. {
  983. cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it);
  984. r(vec, maxCount);
  985. }
  986. template<typename _Tp> static inline
  987. void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>& default_value = std::vector<_Tp>() )
  988. {
  989. if(!node.node)
  990. vec = default_value;
  991. else
  992. {
  993. FileNodeIterator it = node.begin();
  994. read( it, vec );
  995. }
  996. }
  997. static inline
  998. void read( const FileNode& node, std::vector<KeyPoint>& vec, const std::vector<KeyPoint>& default_value )
  999. {
  1000. if(!node.node)
  1001. vec = default_value;
  1002. else
  1003. read(node, vec);
  1004. }
  1005. static inline
  1006. void read( const FileNode& node, std::vector<DMatch>& vec, const std::vector<DMatch>& default_value )
  1007. {
  1008. if(!node.node)
  1009. vec = default_value;
  1010. else
  1011. read(node, vec);
  1012. }
  1013. //! @} FileNode
  1014. //! @relates cv::FileStorage
  1015. //! @{
  1016. /** @brief Writes data to a file storage.
  1017. */
  1018. template<typename _Tp> static inline
  1019. FileStorage& operator << (FileStorage& fs, const _Tp& value)
  1020. {
  1021. if( !fs.isOpened() )
  1022. return fs;
  1023. if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP )
  1024. CV_Error( Error::StsError, "No element name has been given" );
  1025. write( fs, fs.elname, value );
  1026. if( fs.state & FileStorage::INSIDE_MAP )
  1027. fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP;
  1028. return fs;
  1029. }
  1030. /** @brief Writes data to a file storage.
  1031. */
  1032. static inline
  1033. FileStorage& operator << (FileStorage& fs, const char* str)
  1034. {
  1035. return (fs << String(str));
  1036. }
  1037. /** @brief Writes data to a file storage.
  1038. */
  1039. static inline
  1040. FileStorage& operator << (FileStorage& fs, char* value)
  1041. {
  1042. return (fs << String(value));
  1043. }
  1044. //! @} FileStorage
  1045. //! @relates cv::FileNodeIterator
  1046. //! @{
  1047. /** @brief Reads data from a file storage.
  1048. */
  1049. template<typename _Tp> static inline
  1050. FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value)
  1051. {
  1052. read( *it, value, _Tp());
  1053. return ++it;
  1054. }
  1055. /** @brief Reads data from a file storage.
  1056. */
  1057. template<typename _Tp> static inline
  1058. FileNodeIterator& operator >> (FileNodeIterator& it, std::vector<_Tp>& vec)
  1059. {
  1060. cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it);
  1061. r(vec, (size_t)INT_MAX);
  1062. return it;
  1063. }
  1064. //! @} FileNodeIterator
  1065. //! @relates cv::FileNode
  1066. //! @{
  1067. /** @brief Reads data from a file storage.
  1068. */
  1069. template<typename _Tp> static inline
  1070. void operator >> (const FileNode& n, _Tp& value)
  1071. {
  1072. read( n, value, _Tp());
  1073. }
  1074. /** @brief Reads data from a file storage.
  1075. */
  1076. template<typename _Tp> static inline
  1077. void operator >> (const FileNode& n, std::vector<_Tp>& vec)
  1078. {
  1079. FileNodeIterator it = n.begin();
  1080. it >> vec;
  1081. }
  1082. /** @brief Reads KeyPoint from a file storage.
  1083. */
  1084. //It needs special handling because it contains two types of fields, int & float.
  1085. static inline
  1086. void operator >> (const FileNode& n, KeyPoint& kpt)
  1087. {
  1088. FileNodeIterator it = n.begin();
  1089. it >> kpt.pt.x >> kpt.pt.y >> kpt.size >> kpt.angle >> kpt.response >> kpt.octave >> kpt.class_id;
  1090. }
  1091. #ifdef CV__LEGACY_PERSISTENCE
  1092. static inline
  1093. void operator >> (const FileNode& n, std::vector<KeyPoint>& vec)
  1094. {
  1095. read(n, vec);
  1096. }
  1097. static inline
  1098. void operator >> (const FileNode& n, std::vector<DMatch>& vec)
  1099. {
  1100. read(n, vec);
  1101. }
  1102. #endif
  1103. /** @brief Reads DMatch from a file storage.
  1104. */
  1105. //It needs special handling because it contains two types of fields, int & float.
  1106. static inline
  1107. void operator >> (const FileNode& n, DMatch& m)
  1108. {
  1109. FileNodeIterator it = n.begin();
  1110. it >> m.queryIdx >> m.trainIdx >> m.imgIdx >> m.distance;
  1111. }
  1112. //! @} FileNode
  1113. //! @relates cv::FileNodeIterator
  1114. //! @{
  1115. static inline
  1116. bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2)
  1117. {
  1118. return it1.fs == it2.fs && it1.container == it2.container &&
  1119. it1.reader.ptr == it2.reader.ptr && it1.remaining == it2.remaining;
  1120. }
  1121. static inline
  1122. bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2)
  1123. {
  1124. return !(it1 == it2);
  1125. }
  1126. static inline
  1127. ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2)
  1128. {
  1129. return it2.remaining - it1.remaining;
  1130. }
  1131. static inline
  1132. bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2)
  1133. {
  1134. return it1.remaining > it2.remaining;
  1135. }
  1136. //! @} FileNodeIterator
  1137. //! @cond IGNORED
  1138. inline FileNode FileStorage::getFirstTopLevelNode() const { FileNode r = root(); FileNodeIterator it = r.begin(); return it != r.end() ? *it : FileNode(); }
  1139. inline FileNode::FileNode() : fs(0), node(0) {}
  1140. inline FileNode::FileNode(const CvFileStorage* _fs, const CvFileNode* _node) : fs(_fs), node(_node) {}
  1141. inline FileNode::FileNode(const FileNode& _node) : fs(_node.fs), node(_node.node) {}
  1142. inline FileNode& FileNode::operator=(const FileNode& _node) { fs = _node.fs; node = _node.node; return *this; }
  1143. inline bool FileNode::empty() const { return node == 0; }
  1144. inline bool FileNode::isNone() const { return type() == NONE; }
  1145. inline bool FileNode::isSeq() const { return type() == SEQ; }
  1146. inline bool FileNode::isMap() const { return type() == MAP; }
  1147. inline bool FileNode::isInt() const { return type() == INT; }
  1148. inline bool FileNode::isReal() const { return type() == REAL; }
  1149. inline bool FileNode::isString() const { return type() == STR; }
  1150. inline CvFileNode* FileNode::operator *() { return (CvFileNode*)node; }
  1151. inline const CvFileNode* FileNode::operator* () const { return node; }
  1152. inline FileNode::operator int() const { int value; read(*this, value, 0); return value; }
  1153. inline FileNode::operator float() const { float value; read(*this, value, 0.f); return value; }
  1154. inline FileNode::operator double() const { double value; read(*this, value, 0.); return value; }
  1155. inline FileNode::operator String() const { String value; read(*this, value, value); return value; }
  1156. inline double FileNode::real() const { return double(*this); }
  1157. inline String FileNode::string() const { return String(*this); }
  1158. inline Mat FileNode::mat() const { Mat value; read(*this, value, value); return value; }
  1159. inline FileNodeIterator FileNode::begin() const { return FileNodeIterator(fs, node); }
  1160. inline FileNodeIterator FileNode::end() const { return FileNodeIterator(fs, node, size()); }
  1161. inline void FileNode::readRaw( const String& fmt, uchar* vec, size_t len ) const { begin().readRaw( fmt, vec, len ); }
  1162. inline FileNode FileNodeIterator::operator *() const { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); }
  1163. inline FileNode FileNodeIterator::operator ->() const { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); }
  1164. inline String::String(const FileNode& fn): cstr_(0), len_(0) { read(fn, *this, *this); }
  1165. //! @endcond
  1166. CV_EXPORTS void cvStartWriteRawData_Base64(::CvFileStorage * fs, const char* name, int len, const char* dt);
  1167. CV_EXPORTS void cvWriteRawData_Base64(::CvFileStorage * fs, const void* _data, int len);
  1168. CV_EXPORTS void cvEndWriteRawData_Base64(::CvFileStorage * fs);
  1169. CV_EXPORTS void cvWriteMat_Base64(::CvFileStorage* fs, const char* name, const ::CvMat* mat);
  1170. CV_EXPORTS void cvWriteMatND_Base64(::CvFileStorage* fs, const char* name, const ::CvMatND* mat);
  1171. } // cv
  1172. #endif // OPENCV_CORE_PERSISTENCE_HPP