2015-05-02-OpenCV 读取 Matlab .mat 文件的方法

在把 Matlab 转化成 OpenCV(C++) 的过程中,经常会遇见 load .mat 文件这个问题。正巧,Stackoverflow 上有个问题《Converting a .mat file from MATLAB into cv::Mat matrix in OpenCV》就是回答这个的。这篇博文的主要分为两部分,第 1 部分是将这个答案转述一遍,以方便日后需要;第 2 部分是在原答案的基础上的改进,以求在方便程度和灵活性上有一定的提高。

1. (翻译)将 MATLAB 的 .mat 文件转化成 OpenCV 的 cv::Mat 矩阵

由于 OpenCV 没法直接读取 MATLAB 的 .mat 文件,这就需要通过第三方的格式作为两者之间的桥梁。考虑到 OpenCV 的 FileStorage 类提供了 XML/YML 文件的存取功能。
例如,我们有一个如下的 yml 文件,文件名是 demo.yml

%YAML:1.0
    Variable1: !!opencv-matrix
       rows: 4
       cols: 5
       dt: f
       data: [ -1.60522782e-03, -5.93489595e-03, 2.92204670e-03,
           1.14785777e-02, -1.57432575e-02, -2.17529312e-02, 4.05947529e-02,
           6.56594411e-02, 1.24527821e-02, 3.19751091e-02, 5.41692637e-02,
           4.04683389e-02, 2.59191263e-03, 1.15112308e-03, 1.11024221e-02,
           4.03668173e-03, -3.19138430e-02, -9.40114353e-03, 4.93452176e-02,
           5.73473945e-02 ]
    Variable2: !!opencv-matrix
       rows: 7
       cols: 2
       dt: f
       data: [ -2.17529312e-02, 4.05947529e-02, 5.73473945e-02,
           6.56594411e-02, 1.24527821e-02, 3.19751091e-02, 5.41692637e-02,
           4.03668173e-03, -3.19138430e-02, -9.40114353e-03, 4.93452176e-02,
           4.04683389e-02, 2.59191263e-03, 1.15112308e-03 ]

接着,我们就可以用 OpenCV 的 FileStorage 类读取储存在 demo.yml 中的变量了,示例代码如下:

#include <iostream>
#include <string>
 
#include <cv.h>
#include <highgui.h>
 
using namespace cv;
using namespace std;
 
int main (int argc, char * const argv[])
{  
    Mat var1;
    Mat var2;
 
    string demoFile  = "demo.yml";
 
    FileStorage fsDemo( demoFile, FileStorage::READ);
    fsDemo["Variable1"] >> var1;
    fsDemo["Variable2"] >> var2;
 
    cout << "Print the contents of var1:" << endl;
    cout << var1 << endl << endl;
 
    cout << "Print the contents of var2:" << endl;
    cout << var2 << endl;
 
    fsDemo.release();
    return 0;
}

至此,你所需要做的就是写一个你自己的 Matlab parser,类似于如下这样的:

function matlab2opencv( variable, fileName, flag)
 
[rows cols] = size(variable);
 
% Beware of Matlab's linear indexing
variable = variable';
 
% Write mode as default
if ( ~exist('flag','var') )
    flag = 'w';
end
 
if ( ~exist(fileName,'file') || flag == 'w' )
    % New file or write mode specified
    file = fopen( fileName, 'w');
    fprintf( file, '%%YAML:1.0\n');
else
    % Append mode
    file = fopen( fileName, 'a');
end
 
% Write variable header
fprintf( file, '    %s: !!opencv-matrix\n', inputname(1));
fprintf( file, '        rows: %d\n', rows);
fprintf( file, '        cols: %d\n', cols);
fprintf( file, '        dt: f\n');
fprintf( file, '        data: [ ');
 
% Write variable data
for i=1:rows*cols
    fprintf( file, '%.6f', variable(i));
    if (i == rows*cols), break, end
    fprintf( file, ', ');
    if mod(i+1,4) == 0
        fprintf( file, '\n            ');
    end
end
 
fprintf( file, ']\n');
 
fclose(file);

由此,我们就可以将 Matlab 变量储存成 yml 文件,如下所示:

varA = rand( 3, 6);
varB = rand( 7, 2);
 
matlab2opencv( varA, 'newStorageFile.yml');
matlab2opencv( varB, 'newStorageFile.yml', 'a'); % append mode passed by 'a' flag

由此,我们就可以得到 newStorageFile.yml,如下所示:

%YAML:1.0
    varA: !!opencv-matrix
        rows: 3
        cols: 6
        dt: f
        data: [ 0.430207, 0.979748, 0.258065,
            0.262212, 0.221747, 0.318778, 0.184816,
            0.438870, 0.408720, 0.602843, 0.117418,
            0.424167, 0.904881, 0.111119, 0.594896,
            0.711216, 0.296676, 0.507858]
    varB: !!opencv-matrix
        rows: 7
        cols: 2
        dt: f
        data: [ 0.085516, 0.578525, 0.262482,
            0.237284, 0.801015, 0.458849, 0.029220,
            0.963089, 0.928854, 0.546806, 0.730331,
            0.521136, 0.488609, 0.231594]

读取 varAvarB 的方法就跟之前读取 Variable1Variable2 那样。

2. 改进的代码

需求

  • 根据输入的数据类型,自适应地调整写入到 yml 文件的数据类型,以方便后面 cv::Mat 类型的数据访问。

先来一个稍微改动一下,写入 int 类型的代码:

function matlab2opencv_int( variable, fileName, flag)
 
[rows cols] = size(variable);
 
% Beware of Matlab's linear indexing
variable = variable';
 
% Write mode as default
if ( ~exist('flag','var') )
    flag = 'w';
end
 
if ( ~exist(fileName,'file') || flag == 'w' )
    % New file or write mode specified
    file = fopen( fileName, 'w');
    fprintf( file, '%%YAML:1.0\n');
else
    % Append mode
    file = fopen( fileName, 'a');
end
 
% Write variable header
fprintf( file, '    %s: !!opencv-matrix\n', inputname(1));
fprintf( file, '        rows: %d\n', rows);
fprintf( file, '        cols: %d\n', cols);
fprintf( file, '        dt: i\n');
fprintf( file, '        data: [ ');
 
% Write variable data
for i=1:rows*cols
    fprintf( file, '%i', variable(i));
    if (i == rows*cols), break, end
    fprintf( file, ', ');
    if mod(i+1,8) == 0
        fprintf( file, '\n            ');
    end
end
 
fprintf( file, ']\n');
 
fclose(file);

有了上面的基础,下面自动的代码就可以是:

function dym_matlab2opencv(variable, fileName, flag, varClass)
 
% varClass: the variable class waiting for write:
%           'i': for int
%           'f': for float
% flag    : Write mode
%           'w': for write
%           'a': for append
 
[rows, cols] = size(variable);
 
% Beware of Matlab's linear indexing
variable = variable';
 
% Write mode as default
if ( ~exist('flag','var') )
    flag = 'w';
end
 
% float as default
if ( ~exist('varClass','var') )
    if isfloat(variable)
        varClass = 'f';
    else isinteger(variable)
        varClass = 'i';
    end
end
 
if ( ~exist(fileName,'file') || flag == 'w' )
    % New file or write mode specified
    file = fopen( fileName, 'w');
    fprintf( file, '%%YAML:1.0\n');
else
    % Append mode
    file = fopen( fileName, 'a');
end
 
% Write variable header
 
fprintf( file,  '    %s: !!opencv-matrix\n', inputname(1));
fprintf( file,  '        rows: %d\n', rows);
fprintf( file,  '        cols: %d\n', cols);
fprintf( file, ['        dt: ' varClass '\n']);
fprintf( file,  '        data: [ ');
 
% Write variable data
for i=1:rows*cols
    fprintf( file, ['%' varClass], variable(i));
    if (i == rows*cols), break, end
    fprintf( file, ', ');
    if mod(i+1,8) == 0
        fprintf( file, '\n            ');
    end
end
 
fprintf( file, ']\n');
 
fclose(file);

以上,初写于 2015-05-02,更新于 2015-07-23。
首发于 Yimian Dai's Homepage,转载请注明出处。

参考资料

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容