cv.FileStorage - MATLAB File Help
cv.FileStorage

Reading from or writing to a XML/YAML/JSON file storage

S = cv.FileStorage(source)
[S,~] = cv.FileStorage(source)

cv.FileStorage(source, S)
cv.FileStorage(source, X1, X2, ...)
str = cv.FileStorage(source, S)
str = cv.FileStorage(source, X1, X2, ...)

Input

Output

The function reads or writes a MATLAB object from/to a XML, YAML, or JSON file. The file is compatible with OpenCV formats.

The function also supports reading and writing from/to serialized strings. In reading mode, a second dummpy output is used to differentiate between whether the input is a filename or a serialized string.

In writing mode, and when the input argument is not a scalar struct (S), the function creates a scalar struct with default field name and stores the objects (X1, X2, ...) in that struct. In other words the following forms are equivalent:

vars = {'hi', pi, magic(5)};
cv.FileStorage('mydata.xml', vars{:});

S = struct();
S.(name) = vars;
cv.FileStorage('mydata.xml', S);

where name is a default object name generated from the filename.

A few limitations to be aware of:

Example

A quick usage example is shown below.

Writing to a file:

% export two variables to a YAML file
% first is a 2x3 matrix named field1, second is a string named field2
S = struct('field1',randn(2,3), 'field2','this is the second field');
cv.FileStorage('my.yml', S);

Reading from a file:

% import variables from YAML file
S = cv.FileStorage('my.yml');
S.field1  % matrix
S.field2  % string

Replace '.yml' with '.xml' to use XML format.

Example

Below is an example of four variables stored in XML, YAML and JSON files:

>> S = struct('var1',magic(3), 'var2','foo bar', 'var3',1, 'var4',{{2 3}});
>> cv.FileStorage('test.xml', S);
>> cv.FileStorage('test.yml', S);
>> cv.FileStorage('test.json', S);
>> S = cv.FileStorage('test.xml')
S =
    var1: [3x3 double]
    var2: 'foo bar'
    var3: 1
    var4: {[2]  [3]}
<?xml version="1.0"?>
<opencv_storage>
  <var1 type_id="opencv-matrix">
    <rows>3</rows>
    <cols>3</cols>
    <dt>d</dt>
    <data>8. 1. 6. 3. 5. 7. 4. 9. 2.</data>
  </var1>
  <var2>"foo bar"</var2>
  <var3>1.</var3>
  <var4>2. 3.</var4>
</opencv_storage>
%YAML:1.0
---
var1: !!opencv-matrix
   rows: 3
   cols: 3
   dt: d
   data: [ 8., 1., 6., 3., 5., 7., 4., 9., 2. ]
var2: foo bar
var3: 1.
var4:
   - 2.
   - 3.
{
    "var1": {
        "type_id": "opencv-matrix",
        "rows": 3,
        "cols": 3,
        "dt": "d",
        "data": [ 8., 1., 6., 3., 5., 7., 4., 9., 2. ]
    },
    "var2": "foo bar",
    "var3": 1.,
    "var4": [
        2.,
        3.
    ]
}
See also