persistence.hpp 47 KB

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