persistence.hpp 49 KB

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