persistence.hpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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 ocvWrite 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 Returns the normalized object name for the specified name of a file.
  388. @param filename Name of a file
  389. @returns The normalized object name.
  390. */
  391. static String getDefaultObjectName(const String& filename);
  392. /** @brief Returns the current format.
  393. * @returns The current format, see FileStorage::Mode
  394. */
  395. CV_WRAP int getFormat() const;
  396. Ptr<CvFileStorage> fs; //!< the underlying C FileStorage structure
  397. String elname; //!< the currently written element
  398. std::vector<char> structs; //!< the stack of written structures
  399. int state; //!< the writer state
  400. };
  401. template<> CV_EXPORTS void DefaultDeleter<CvFileStorage>::operator ()(CvFileStorage* obj) const;
  402. /** @brief File Storage Node class.
  403. The node is used to store each and every element of the file storage opened for reading. When
  404. XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of
  405. nodes. Each node can be a "leaf" that is contain a single number or a string, or be a collection of
  406. other nodes. There can be named collections (mappings) where each element has a name and it is
  407. accessed by a name, and ordered collections (sequences) where elements do not have names but rather
  408. accessed by index. Type of the file node can be determined using FileNode::type method.
  409. Note that file nodes are only used for navigating file storages opened for reading. When a file
  410. storage is opened for writing, no data is stored in memory after it is written.
  411. */
  412. class CV_EXPORTS_W_SIMPLE FileNode
  413. {
  414. public:
  415. //! type of the file storage node
  416. enum Type
  417. {
  418. NONE = 0, //!< empty node
  419. INT = 1, //!< an integer
  420. REAL = 2, //!< floating-point number
  421. FLOAT = REAL, //!< synonym or REAL
  422. STR = 3, //!< text string in UTF-8 encoding
  423. STRING = STR, //!< synonym for STR
  424. REF = 4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others
  425. SEQ = 5, //!< sequence
  426. MAP = 6, //!< mapping
  427. TYPE_MASK = 7,
  428. FLOW = 8, //!< compact representation of a sequence or mapping. Used only by YAML writer
  429. USER = 16, //!< a registered object (e.g. a matrix)
  430. EMPTY = 32, //!< empty structure (sequence or mapping)
  431. NAMED = 64 //!< the node has a name (i.e. it is element of a mapping)
  432. };
  433. /** @brief The constructors.
  434. These constructors are used to create a default file node, construct it from obsolete structures or
  435. from the another file node.
  436. */
  437. CV_WRAP FileNode();
  438. /** @overload
  439. @param fs Pointer to the obsolete file storage structure.
  440. @param node File node to be used as initialization for the created file node.
  441. */
  442. FileNode(const CvFileStorage* fs, const CvFileNode* node);
  443. /** @overload
  444. @param node File node to be used as initialization for the created file node.
  445. */
  446. FileNode(const FileNode& node);
  447. /** @brief Returns element of a mapping node or a sequence node.
  448. @param nodename Name of an element in the mapping node.
  449. @returns Returns the element with the given identifier.
  450. */
  451. FileNode operator[](const String& nodename) const;
  452. /** @overload
  453. @param nodename Name of an element in the mapping node.
  454. */
  455. CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const;
  456. /** @overload
  457. @param i Index of an element in the sequence node.
  458. */
  459. CV_WRAP_AS(at) FileNode operator[](int i) const;
  460. /** @brief Returns keys of a mapping node.
  461. @returns Keys of a mapping node.
  462. */
  463. CV_WRAP std::vector<String> keys() const;
  464. /** @brief Returns type of the node.
  465. @returns Type of the node. See FileNode::Type
  466. */
  467. CV_WRAP int type() const;
  468. //! returns true if the node is empty
  469. CV_WRAP bool empty() const;
  470. //! returns true if the node is a "none" object
  471. CV_WRAP bool isNone() const;
  472. //! returns true if the node is a sequence
  473. CV_WRAP bool isSeq() const;
  474. //! returns true if the node is a mapping
  475. CV_WRAP bool isMap() const;
  476. //! returns true if the node is an integer
  477. CV_WRAP bool isInt() const;
  478. //! returns true if the node is a floating-point number
  479. CV_WRAP bool isReal() const;
  480. //! returns true if the node is a text string
  481. CV_WRAP bool isString() const;
  482. //! returns true if the node has a name
  483. CV_WRAP bool isNamed() const;
  484. //! returns the node name or an empty string if the node is nameless
  485. CV_WRAP String name() const;
  486. //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise.
  487. CV_WRAP size_t size() const;
  488. //! returns the node content as an integer. If the node stores floating-point number, it is rounded.
  489. operator int() const;
  490. //! returns the node content as float
  491. operator float() const;
  492. //! returns the node content as double
  493. operator double() const;
  494. //! returns the node content as text string
  495. operator String() const;
  496. operator std::string() const;
  497. //! returns pointer to the underlying file node
  498. CvFileNode* operator *();
  499. //! returns pointer to the underlying file node
  500. const CvFileNode* operator* () const;
  501. //! returns iterator pointing to the first node element
  502. FileNodeIterator begin() const;
  503. //! returns iterator pointing to the element following the last node element
  504. FileNodeIterator end() const;
  505. /** @brief Reads node elements to the buffer with the specified format.
  506. Usually it is more convenient to use operator `>>` instead of this method.
  507. @param fmt Specification of each array element. See @ref format_spec "format specification"
  508. @param vec Pointer to the destination array.
  509. @param len Number of bytes to read (buffer size limit). If it is greater than number of
  510. remaining elements then all of them will be read.
  511. */
  512. void readRaw( const String& fmt, uchar* vec, size_t len ) const;
  513. //! reads the registered object and returns pointer to it
  514. void* readObj() const;
  515. //! Simplified reading API to use with bindings.
  516. CV_WRAP double real() const;
  517. //! Simplified reading API to use with bindings.
  518. CV_WRAP String string() const;
  519. //! Simplified reading API to use with bindings.
  520. CV_WRAP Mat mat() const;
  521. // do not use wrapper pointer classes for better efficiency
  522. const CvFileStorage* fs;
  523. const CvFileNode* node;
  524. };
  525. /** @brief used to iterate through sequences and mappings.
  526. A standard STL notation, with node.begin(), node.end() denoting the beginning and the end of a
  527. sequence, stored in node. See the data reading sample in the beginning of the section.
  528. */
  529. class CV_EXPORTS FileNodeIterator
  530. {
  531. public:
  532. /** @brief The constructors.
  533. These constructors are used to create a default iterator, set it to specific element in a file node
  534. or construct it from another iterator.
  535. */
  536. FileNodeIterator();
  537. /** @overload
  538. @param fs File storage for the iterator.
  539. @param node File node for the iterator.
  540. @param ofs Index of the element in the node. The created iterator will point to this element.
  541. */
  542. FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0);
  543. /** @overload
  544. @param it Iterator to be used as initialization for the created iterator.
  545. */
  546. FileNodeIterator(const FileNodeIterator& it);
  547. //! returns the currently observed element
  548. FileNode operator *() const;
  549. //! accesses the currently observed element methods
  550. FileNode operator ->() const;
  551. //! moves iterator to the next node
  552. FileNodeIterator& operator ++ ();
  553. //! moves iterator to the next node
  554. FileNodeIterator operator ++ (int);
  555. //! moves iterator to the previous node
  556. FileNodeIterator& operator -- ();
  557. //! moves iterator to the previous node
  558. FileNodeIterator operator -- (int);
  559. //! moves iterator forward by the specified offset (possibly negative)
  560. FileNodeIterator& operator += (int ofs);
  561. //! moves iterator backward by the specified offset (possibly negative)
  562. FileNodeIterator& operator -= (int ofs);
  563. /** @brief Reads node elements to the buffer with the specified format.
  564. Usually it is more convenient to use operator `>>` instead of this method.
  565. @param fmt Specification of each array element. See @ref format_spec "format specification"
  566. @param vec Pointer to the destination array.
  567. @param len Number of bytes to read (buffer size limit). If it is greater than number of
  568. remaining elements then all of them will be read.
  569. */
  570. FileNodeIterator& readRaw( const String& fmt, uchar* vec,
  571. size_t len=(size_t)INT_MAX );
  572. struct SeqReader
  573. {
  574. int header_size;
  575. void* seq; /* sequence, beign read; CvSeq */
  576. void* block; /* current block; CvSeqBlock */
  577. schar* ptr; /* pointer to element be read next */
  578. schar* block_min; /* pointer to the beginning of block */
  579. schar* block_max; /* pointer to the end of block */
  580. int delta_index;/* = seq->first->start_index */
  581. schar* prev_elem; /* pointer to previous element */
  582. };
  583. const CvFileStorage* fs;
  584. const CvFileNode* container;
  585. SeqReader reader;
  586. size_t remaining;
  587. };
  588. //! @} core_xml
  589. /////////////////// XML & YAML I/O implementation //////////////////
  590. //! @relates cv::FileStorage
  591. //! @{
  592. CV_EXPORTS void write( FileStorage& fs, const String& name, int value );
  593. CV_EXPORTS void write( FileStorage& fs, const String& name, float value );
  594. CV_EXPORTS void write( FileStorage& fs, const String& name, double value );
  595. CV_EXPORTS void write( FileStorage& fs, const String& name, const String& value );
  596. CV_EXPORTS void write( FileStorage& fs, const String& name, const Mat& value );
  597. CV_EXPORTS void write( FileStorage& fs, const String& name, const SparseMat& value );
  598. #ifdef CV__LEGACY_PERSISTENCE
  599. CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector<KeyPoint>& value);
  600. CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector<DMatch>& value);
  601. #endif
  602. CV_EXPORTS void writeScalar( FileStorage& fs, int value );
  603. CV_EXPORTS void writeScalar( FileStorage& fs, float value );
  604. CV_EXPORTS void writeScalar( FileStorage& fs, double value );
  605. CV_EXPORTS void writeScalar( FileStorage& fs, const String& value );
  606. //! @}
  607. //! @relates cv::FileNode
  608. //! @{
  609. CV_EXPORTS void read(const FileNode& node, int& value, int default_value);
  610. CV_EXPORTS void read(const FileNode& node, float& value, float default_value);
  611. CV_EXPORTS void read(const FileNode& node, double& value, double default_value);
  612. CV_EXPORTS void read(const FileNode& node, String& value, const String& default_value);
  613. CV_EXPORTS void read(const FileNode& node, std::string& value, const std::string& default_value);
  614. CV_EXPORTS void read(const FileNode& node, Mat& mat, const Mat& default_mat = Mat() );
  615. CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat = SparseMat() );
  616. #ifdef CV__LEGACY_PERSISTENCE
  617. CV_EXPORTS void read(const FileNode& node, std::vector<KeyPoint>& keypoints);
  618. CV_EXPORTS void read(const FileNode& node, std::vector<DMatch>& matches);
  619. #endif
  620. CV_EXPORTS void read(const FileNode& node, KeyPoint& value, const KeyPoint& default_value);
  621. CV_EXPORTS void read(const FileNode& node, DMatch& value, const DMatch& default_value);
  622. template<typename _Tp> static inline void read(const FileNode& node, Point_<_Tp>& value, const Point_<_Tp>& default_value)
  623. {
  624. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  625. value = temp.size() != 2 ? default_value : Point_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]));
  626. }
  627. template<typename _Tp> static inline void read(const FileNode& node, Point3_<_Tp>& value, const Point3_<_Tp>& default_value)
  628. {
  629. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  630. value = temp.size() != 3 ? default_value : Point3_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]),
  631. saturate_cast<_Tp>(temp[2]));
  632. }
  633. template<typename _Tp> static inline void read(const FileNode& node, Size_<_Tp>& value, const Size_<_Tp>& default_value)
  634. {
  635. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  636. value = temp.size() != 2 ? default_value : Size_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]));
  637. }
  638. template<typename _Tp> static inline void read(const FileNode& node, Complex<_Tp>& value, const Complex<_Tp>& default_value)
  639. {
  640. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  641. value = temp.size() != 2 ? default_value : Complex<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]));
  642. }
  643. template<typename _Tp> static inline void read(const FileNode& node, Rect_<_Tp>& value, const Rect_<_Tp>& default_value)
  644. {
  645. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  646. value = temp.size() != 4 ? default_value : Rect_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]),
  647. saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3]));
  648. }
  649. template<typename _Tp, int cn> static inline void read(const FileNode& node, Vec<_Tp, cn>& value, const Vec<_Tp, cn>& default_value)
  650. {
  651. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  652. value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]);
  653. }
  654. template<typename _Tp> static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value)
  655. {
  656. std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
  657. value = temp.size() != 4 ? default_value : Scalar_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]),
  658. saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3]));
  659. }
  660. static inline void read(const FileNode& node, Range& value, const Range& default_value)
  661. {
  662. Point2i temp(value.start, value.end); const Point2i default_temp = Point2i(default_value.start, default_value.end);
  663. read(node, temp, default_temp);
  664. value.start = temp.x; value.end = temp.y;
  665. }
  666. //! @}
  667. /** @brief Writes string to a file storage.
  668. @relates cv::FileStorage
  669. */
  670. CV_EXPORTS FileStorage& operator << (FileStorage& fs, const String& str);
  671. //! @cond IGNORED
  672. namespace internal
  673. {
  674. class CV_EXPORTS WriteStructContext
  675. {
  676. public:
  677. WriteStructContext(FileStorage& _fs, const String& name, int flags, const String& typeName = String());
  678. ~WriteStructContext();
  679. private:
  680. FileStorage* fs;
  681. };
  682. template<typename _Tp, int numflag> class VecWriterProxy
  683. {
  684. public:
  685. VecWriterProxy( FileStorage* _fs ) : fs(_fs) {}
  686. void operator()(const std::vector<_Tp>& vec) const
  687. {
  688. size_t count = vec.size();
  689. for (size_t i = 0; i < count; i++)
  690. write(*fs, vec[i]);
  691. }
  692. private:
  693. FileStorage* fs;
  694. };
  695. template<typename _Tp> class VecWriterProxy<_Tp, 1>
  696. {
  697. public:
  698. VecWriterProxy( FileStorage* _fs ) : fs(_fs) {}
  699. void operator()(const std::vector<_Tp>& vec) const
  700. {
  701. int _fmt = traits::SafeFmt<_Tp>::fmt;
  702. char fmt[] = { (char)((_fmt >> 8) + '1'), (char)_fmt, '\0' };
  703. fs->writeRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, vec.size() * sizeof(_Tp));
  704. }
  705. private:
  706. FileStorage* fs;
  707. };
  708. template<typename _Tp, int numflag> class VecReaderProxy
  709. {
  710. public:
  711. VecReaderProxy( FileNodeIterator* _it ) : it(_it) {}
  712. void operator()(std::vector<_Tp>& vec, size_t count) const
  713. {
  714. count = std::min(count, it->remaining);
  715. vec.resize(count);
  716. for (size_t i = 0; i < count; i++, ++(*it))
  717. read(**it, vec[i], _Tp());
  718. }
  719. private:
  720. FileNodeIterator* it;
  721. };
  722. template<typename _Tp> class VecReaderProxy<_Tp, 1>
  723. {
  724. public:
  725. VecReaderProxy( FileNodeIterator* _it ) : it(_it) {}
  726. void operator()(std::vector<_Tp>& vec, size_t count) const
  727. {
  728. size_t remaining = it->remaining;
  729. size_t cn = DataType<_Tp>::channels;
  730. int _fmt = traits::SafeFmt<_Tp>::fmt;
  731. CV_Assert((_fmt >> 8) < 9);
  732. char fmt[] = { (char)((_fmt >> 8)+'1'), (char)_fmt, '\0' };
  733. CV_Assert((remaining % cn) == 0);
  734. size_t remaining1 = remaining / cn;
  735. count = count < remaining1 ? count : remaining1;
  736. vec.resize(count);
  737. it->readRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp));
  738. }
  739. private:
  740. FileNodeIterator* it;
  741. };
  742. } // internal
  743. //! @endcond
  744. //! @relates cv::FileStorage
  745. //! @{
  746. template<typename _Tp> static inline
  747. void write(FileStorage& fs, const _Tp& value)
  748. {
  749. write(fs, String(), value);
  750. }
  751. template<> inline
  752. void write( FileStorage& fs, const int& value )
  753. {
  754. writeScalar(fs, value);
  755. }
  756. template<> inline
  757. void write( FileStorage& fs, const float& value )
  758. {
  759. writeScalar(fs, value);
  760. }
  761. template<> inline
  762. void write( FileStorage& fs, const double& value )
  763. {
  764. writeScalar(fs, value);
  765. }
  766. template<> inline
  767. void write( FileStorage& fs, const String& value )
  768. {
  769. writeScalar(fs, value);
  770. }
  771. template<typename _Tp> static inline
  772. void write(FileStorage& fs, const Point_<_Tp>& pt )
  773. {
  774. write(fs, pt.x);
  775. write(fs, pt.y);
  776. }
  777. template<typename _Tp> static inline
  778. void write(FileStorage& fs, const Point3_<_Tp>& pt )
  779. {
  780. write(fs, pt.x);
  781. write(fs, pt.y);
  782. write(fs, pt.z);
  783. }
  784. template<typename _Tp> static inline
  785. void write(FileStorage& fs, const Size_<_Tp>& sz )
  786. {
  787. write(fs, sz.width);
  788. write(fs, sz.height);
  789. }
  790. template<typename _Tp> static inline
  791. void write(FileStorage& fs, const Complex<_Tp>& c )
  792. {
  793. write(fs, c.re);
  794. write(fs, c.im);
  795. }
  796. template<typename _Tp> static inline
  797. void write(FileStorage& fs, const Rect_<_Tp>& r )
  798. {
  799. write(fs, r.x);
  800. write(fs, r.y);
  801. write(fs, r.width);
  802. write(fs, r.height);
  803. }
  804. template<typename _Tp, int cn> static inline
  805. void write(FileStorage& fs, const Vec<_Tp, cn>& v )
  806. {
  807. for(int i = 0; i < cn; i++)
  808. write(fs, v.val[i]);
  809. }
  810. template<typename _Tp> static inline
  811. void write(FileStorage& fs, const Scalar_<_Tp>& s )
  812. {
  813. write(fs, s.val[0]);
  814. write(fs, s.val[1]);
  815. write(fs, s.val[2]);
  816. write(fs, s.val[3]);
  817. }
  818. static inline
  819. void write(FileStorage& fs, const Range& r )
  820. {
  821. write(fs, r.start);
  822. write(fs, r.end);
  823. }
  824. template<typename _Tp> static inline
  825. void write( FileStorage& fs, const std::vector<_Tp>& vec )
  826. {
  827. cv::internal::VecWriterProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> w(&fs);
  828. w(vec);
  829. }
  830. template<typename _Tp> static inline
  831. void write(FileStorage& fs, const String& name, const Point_<_Tp>& pt )
  832. {
  833. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  834. write(fs, pt);
  835. }
  836. template<typename _Tp> static inline
  837. void write(FileStorage& fs, const String& name, const Point3_<_Tp>& pt )
  838. {
  839. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  840. write(fs, pt);
  841. }
  842. template<typename _Tp> static inline
  843. void write(FileStorage& fs, const String& name, const Size_<_Tp>& sz )
  844. {
  845. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  846. write(fs, sz);
  847. }
  848. template<typename _Tp> static inline
  849. void write(FileStorage& fs, const String& name, const Complex<_Tp>& c )
  850. {
  851. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  852. write(fs, c);
  853. }
  854. template<typename _Tp> static inline
  855. void write(FileStorage& fs, const String& name, const Rect_<_Tp>& r )
  856. {
  857. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  858. write(fs, r);
  859. }
  860. template<typename _Tp, int cn> static inline
  861. void write(FileStorage& fs, const String& name, const Vec<_Tp, cn>& v )
  862. {
  863. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  864. write(fs, v);
  865. }
  866. template<typename _Tp> static inline
  867. void write(FileStorage& fs, const String& name, const Scalar_<_Tp>& s )
  868. {
  869. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  870. write(fs, s);
  871. }
  872. static inline
  873. void write(FileStorage& fs, const String& name, const Range& r )
  874. {
  875. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  876. write(fs, r);
  877. }
  878. static inline
  879. void write(FileStorage& fs, const String& name, const KeyPoint& kpt)
  880. {
  881. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  882. write(fs, kpt.pt.x);
  883. write(fs, kpt.pt.y);
  884. write(fs, kpt.size);
  885. write(fs, kpt.angle);
  886. write(fs, kpt.response);
  887. write(fs, kpt.octave);
  888. write(fs, kpt.class_id);
  889. }
  890. static inline
  891. void write(FileStorage& fs, const String& name, const DMatch& m)
  892. {
  893. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
  894. write(fs, m.queryIdx);
  895. write(fs, m.trainIdx);
  896. write(fs, m.imgIdx);
  897. write(fs, m.distance);
  898. }
  899. template<typename _Tp> static inline
  900. void write( FileStorage& fs, const String& name, const std::vector<_Tp>& vec )
  901. {
  902. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0));
  903. write(fs, vec);
  904. }
  905. template<typename _Tp> static inline
  906. void write( FileStorage& fs, const String& name, const std::vector< std::vector<_Tp> >& vec )
  907. {
  908. cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ);
  909. for(size_t i = 0; i < vec.size(); i++)
  910. {
  911. cv::internal::WriteStructContext ws_(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0));
  912. write(fs, vec[i]);
  913. }
  914. }
  915. #ifdef CV__LEGACY_PERSISTENCE
  916. // This code is not needed anymore, but it is preserved here to keep source compatibility
  917. // Implementation is similar to templates instantiations
  918. static inline void write(FileStorage& fs, const KeyPoint& kpt) { write(fs, String(), kpt); }
  919. static inline void write(FileStorage& fs, const DMatch& m) { write(fs, String(), m); }
  920. static inline void write(FileStorage& fs, const std::vector<KeyPoint>& vec)
  921. {
  922. cv::internal::VecWriterProxy<KeyPoint, 0> w(&fs);
  923. w(vec);
  924. }
  925. static inline void write(FileStorage& fs, const std::vector<DMatch>& vec)
  926. {
  927. cv::internal::VecWriterProxy<DMatch, 0> w(&fs);
  928. w(vec);
  929. }
  930. #endif
  931. //! @} FileStorage
  932. //! @relates cv::FileNode
  933. //! @{
  934. static inline
  935. void read(const FileNode& node, bool& value, bool default_value)
  936. {
  937. int temp;
  938. read(node, temp, (int)default_value);
  939. value = temp != 0;
  940. }
  941. static inline
  942. void read(const FileNode& node, uchar& value, uchar default_value)
  943. {
  944. int temp;
  945. read(node, temp, (int)default_value);
  946. value = saturate_cast<uchar>(temp);
  947. }
  948. static inline
  949. void read(const FileNode& node, schar& value, schar default_value)
  950. {
  951. int temp;
  952. read(node, temp, (int)default_value);
  953. value = saturate_cast<schar>(temp);
  954. }
  955. static inline
  956. void read(const FileNode& node, ushort& value, ushort default_value)
  957. {
  958. int temp;
  959. read(node, temp, (int)default_value);
  960. value = saturate_cast<ushort>(temp);
  961. }
  962. static inline
  963. void read(const FileNode& node, short& value, short default_value)
  964. {
  965. int temp;
  966. read(node, temp, (int)default_value);
  967. value = saturate_cast<short>(temp);
  968. }
  969. template<typename _Tp> static inline
  970. void read( FileNodeIterator& it, std::vector<_Tp>& vec, size_t maxCount = (size_t)INT_MAX )
  971. {
  972. cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it);
  973. r(vec, maxCount);
  974. }
  975. template<typename _Tp> static inline
  976. void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>& default_value = std::vector<_Tp>() )
  977. {
  978. if(!node.node)
  979. vec = default_value;
  980. else
  981. {
  982. FileNodeIterator it = node.begin();
  983. read( it, vec );
  984. }
  985. }
  986. static inline
  987. void read( const FileNode& node, std::vector<KeyPoint>& vec, const std::vector<KeyPoint>& default_value )
  988. {
  989. if(!node.node)
  990. vec = default_value;
  991. else
  992. read(node, vec);
  993. }
  994. static inline
  995. void read( const FileNode& node, std::vector<DMatch>& vec, const std::vector<DMatch>& default_value )
  996. {
  997. if(!node.node)
  998. vec = default_value;
  999. else
  1000. read(node, vec);
  1001. }
  1002. //! @} FileNode
  1003. //! @relates cv::FileStorage
  1004. //! @{
  1005. /** @brief Writes data to a file storage.
  1006. */
  1007. template<typename _Tp> static inline
  1008. FileStorage& operator << (FileStorage& fs, const _Tp& value)
  1009. {
  1010. if( !fs.isOpened() )
  1011. return fs;
  1012. if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP )
  1013. CV_Error( Error::StsError, "No element name has been given" );
  1014. write( fs, fs.elname, value );
  1015. if( fs.state & FileStorage::INSIDE_MAP )
  1016. fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP;
  1017. return fs;
  1018. }
  1019. /** @brief Writes data to a file storage.
  1020. */
  1021. static inline
  1022. FileStorage& operator << (FileStorage& fs, const char* str)
  1023. {
  1024. return (fs << String(str));
  1025. }
  1026. /** @brief Writes data to a file storage.
  1027. */
  1028. static inline
  1029. FileStorage& operator << (FileStorage& fs, char* value)
  1030. {
  1031. return (fs << String(value));
  1032. }
  1033. //! @} FileStorage
  1034. //! @relates cv::FileNodeIterator
  1035. //! @{
  1036. /** @brief Reads data from a file storage.
  1037. */
  1038. template<typename _Tp> static inline
  1039. FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value)
  1040. {
  1041. read( *it, value, _Tp());
  1042. return ++it;
  1043. }
  1044. /** @brief Reads data from a file storage.
  1045. */
  1046. template<typename _Tp> static inline
  1047. FileNodeIterator& operator >> (FileNodeIterator& it, std::vector<_Tp>& vec)
  1048. {
  1049. cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it);
  1050. r(vec, (size_t)INT_MAX);
  1051. return it;
  1052. }
  1053. //! @} FileNodeIterator
  1054. //! @relates cv::FileNode
  1055. //! @{
  1056. /** @brief Reads data from a file storage.
  1057. */
  1058. template<typename _Tp> static inline
  1059. void operator >> (const FileNode& n, _Tp& value)
  1060. {
  1061. read( n, value, _Tp());
  1062. }
  1063. /** @brief Reads data from a file storage.
  1064. */
  1065. template<typename _Tp> static inline
  1066. void operator >> (const FileNode& n, std::vector<_Tp>& vec)
  1067. {
  1068. FileNodeIterator it = n.begin();
  1069. it >> vec;
  1070. }
  1071. /** @brief Reads KeyPoint from a file storage.
  1072. */
  1073. //It needs special handling because it contains two types of fields, int & float.
  1074. static inline
  1075. void operator >> (const FileNode& n, KeyPoint& kpt)
  1076. {
  1077. FileNodeIterator it = n.begin();
  1078. it >> kpt.pt.x >> kpt.pt.y >> kpt.size >> kpt.angle >> kpt.response >> kpt.octave >> kpt.class_id;
  1079. }
  1080. #ifdef CV__LEGACY_PERSISTENCE
  1081. static inline
  1082. void operator >> (const FileNode& n, std::vector<KeyPoint>& vec)
  1083. {
  1084. read(n, vec);
  1085. }
  1086. static inline
  1087. void operator >> (const FileNode& n, std::vector<DMatch>& vec)
  1088. {
  1089. read(n, vec);
  1090. }
  1091. #endif
  1092. /** @brief Reads DMatch from a file storage.
  1093. */
  1094. //It needs special handling because it contains two types of fields, int & float.
  1095. static inline
  1096. void operator >> (const FileNode& n, DMatch& m)
  1097. {
  1098. FileNodeIterator it = n.begin();
  1099. it >> m.queryIdx >> m.trainIdx >> m.imgIdx >> m.distance;
  1100. }
  1101. //! @} FileNode
  1102. //! @relates cv::FileNodeIterator
  1103. //! @{
  1104. static inline
  1105. bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2)
  1106. {
  1107. return it1.fs == it2.fs && it1.container == it2.container &&
  1108. it1.reader.ptr == it2.reader.ptr && it1.remaining == it2.remaining;
  1109. }
  1110. static inline
  1111. bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2)
  1112. {
  1113. return !(it1 == it2);
  1114. }
  1115. static inline
  1116. ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2)
  1117. {
  1118. return it2.remaining - it1.remaining;
  1119. }
  1120. static inline
  1121. bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2)
  1122. {
  1123. return it1.remaining > it2.remaining;
  1124. }
  1125. //! @} FileNodeIterator
  1126. //! @cond IGNORED
  1127. inline FileNode FileStorage::getFirstTopLevelNode() const { FileNode r = root(); FileNodeIterator it = r.begin(); return it != r.end() ? *it : FileNode(); }
  1128. inline FileNode::FileNode() : fs(0), node(0) {}
  1129. inline FileNode::FileNode(const CvFileStorage* _fs, const CvFileNode* _node) : fs(_fs), node(_node) {}
  1130. inline FileNode::FileNode(const FileNode& _node) : fs(_node.fs), node(_node.node) {}
  1131. inline bool FileNode::empty() const { return node == 0; }
  1132. inline bool FileNode::isNone() const { return type() == NONE; }
  1133. inline bool FileNode::isSeq() const { return type() == SEQ; }
  1134. inline bool FileNode::isMap() const { return type() == MAP; }
  1135. inline bool FileNode::isInt() const { return type() == INT; }
  1136. inline bool FileNode::isReal() const { return type() == REAL; }
  1137. inline bool FileNode::isString() const { return type() == STR; }
  1138. inline CvFileNode* FileNode::operator *() { return (CvFileNode*)node; }
  1139. inline const CvFileNode* FileNode::operator* () const { return node; }
  1140. inline FileNode::operator int() const { int value; read(*this, value, 0); return value; }
  1141. inline FileNode::operator float() const { float value; read(*this, value, 0.f); return value; }
  1142. inline FileNode::operator double() const { double value; read(*this, value, 0.); return value; }
  1143. inline FileNode::operator String() const { String value; read(*this, value, value); return value; }
  1144. inline double FileNode::real() const { return double(*this); }
  1145. inline String FileNode::string() const { return String(*this); }
  1146. inline Mat FileNode::mat() const { Mat value; read(*this, value, value); return value; }
  1147. inline FileNodeIterator FileNode::begin() const { return FileNodeIterator(fs, node); }
  1148. inline FileNodeIterator FileNode::end() const { return FileNodeIterator(fs, node, size()); }
  1149. inline void FileNode::readRaw( const String& fmt, uchar* vec, size_t len ) const { begin().readRaw( fmt, vec, len ); }
  1150. inline FileNode FileNodeIterator::operator *() const { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); }
  1151. inline FileNode FileNodeIterator::operator ->() const { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); }
  1152. inline String::String(const FileNode& fn): cstr_(0), len_(0) { read(fn, *this, *this); }
  1153. //! @endcond
  1154. CV_EXPORTS void cvStartWriteRawData_Base64(::CvFileStorage * fs, const char* name, int len, const char* dt);
  1155. CV_EXPORTS void cvWriteRawData_Base64(::CvFileStorage * fs, const void* _data, int len);
  1156. CV_EXPORTS void cvEndWriteRawData_Base64(::CvFileStorage * fs);
  1157. CV_EXPORTS void cvWriteMat_Base64(::CvFileStorage* fs, const char* name, const ::CvMat* mat);
  1158. CV_EXPORTS void cvWriteMatND_Base64(::CvFileStorage* fs, const char* name, const ::CvMatND* mat);
  1159. } // cv
  1160. #endif // OPENCV_CORE_PERSISTENCE_HPP