Serialization Functionality
Demonstrate the usage of OpenCV serialization functionality.
This program demonstrates the use of cv.FileStorage for serialization in OpenCV. FileStorage allows you to serialize to various formats specified by the file end type. You should try using different file extensions (e.g. .yaml, .yml, .xml, .xml.gz, .yaml.gz, etc.)
Sources:
Contents
Data
collect variables inside a struct (including cell array of strings, matrices/vectors, structs, scalar numerics, and strings)
S = struct(); S.images = {'image1.jpg', 'myfi.png', '../data/baboon.jpg'}; S.R = eye(3); S.T = zeros(3,1); S.mdata.A = int32(97); S.mdata.X = pi; S.mdata.id = 'mydata1234'; display(S)
S = struct with fields: images: {'image1.jpg' 'myfi.png' '../data/baboon.jpg'} R: [3×3 double] T: [3×1 double] mdata: [1×1 struct]
Write
save data as YAML file
fname = fullfile(tempdir(), 'out.yml');
cv.FileStorage(fname, S);
show contents of YAML file
type(fname)
%YAML:1.0 --- images: - "image1.jpg" - "myfi.png" - "../data/baboon.jpg" R: !!opencv-matrix rows: 3 cols: 3 dt: d data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1. ] T: !!opencv-matrix rows: 3 cols: 1 dt: d data: [ 0., 0., 0. ] mdata: A: 97 X: 3.1415926535897931e+00 id: mydata1234
we can also save as GZIP-compressed file
fnameGZ = fullfile(tempdir(), 'out.xml.gz');
cv.FileStorage(fnameGZ, S);
extract and show contents of XML file
f = gunzip(fnameGZ); type(f{1})
<?xml version="1.0"?> <opencv_storage> <images> image1.jpg myfi.png "../data/baboon.jpg"</images> <R type_id="opencv-matrix"> <rows>3</rows> <cols>3</cols> <dt>d</dt> <data> 1. 0. 0. 0. 1. 0. 0. 0. 1.</data></R> <T type_id="opencv-matrix"> <rows>3</rows> <cols>1</cols> <dt>d</dt> <data> 0. 0. 0.</data></T> <mdata> <A>97</A> <X>3.1415926535897931e+00</X> <id>mydata1234</id></mdata> </opencv_storage>
Read
load data from YAML file
SS = cv.FileStorage(fname);
display(SS)
%assert(isequal(S,SS))
SS = struct with fields: images: {'image1.jpg' 'myfi.png' '../data/baboon.jpg'} R: [3×3 double] T: [3×1 double] mdata: [1×1 struct]
Read from string
a serialized string
str = { '%YAML:1.0' '# some comment' 'mdata:' ' A: 97' ' X: 3.1415926535897931e+00' ' id: mydata1234' ' seq: [1, 2, 3]' ' map: {name: John Smith, age: 11}' }; str = sprintf('%s\n', str{:}); display(str)
str = '%YAML:1.0 # some comment mdata: A: 97 X: 3.1415926535897931e+00 id: mydata1234 seq: [1, 2, 3] map: {name: John Smith, age: 11} '
load data from string
[M,~] = cv.FileStorage(str); display(M.mdata)
A: 97 X: 3.1416 id: 'mydata1234' seq: {[1] [2] [3]} map: [1×1 struct]
Write to string
encode data as a YAML string
str2 = cv.FileStorage('.yml', M);
display(str2)
str2 = '%YAML:1.0 --- mdata: A: 97. X: 3.1415926535897931e+00 id: mydata1234 seq: - 1. - 2. - 3. map: name: John Smith age: 11. '