使用C++将OpenCV中Mat的数据写下二进制文件,用Matlab读出

使用C++将OpenCV中Mat的数据写入二进制文件,用Matlab读出

在使用OpenCV开发程序时,如果想查看矩阵数据,比较费劲,而matlab查看数据很方便,有一种方法,是matlab和c++混合编程,可以用matlab访问c++的内存,可惜我不会这种方式,所以我就把数据写到文件里,用matlab读出来,然后用matlab各种高级功能查看数据的值。


1、将Mat的数据写入指定文件

为了方便拿来主义者,我直接把这个函数贴出来,你只要把代码拷贝到自己的代码里,就可以直接用了。如果有问题,赶紧评论,我会尽快看看问题出在哪里

#include <iostream>
#include <fstream>
#include <string>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;

int abWrite(const Mat &im, const string &fname)
{
  ofstream ouF;
  ouF.open(fname.c_str(), std::ofstream::binary);
  if (!ouF)
  {
    cerr << "failed to open the file : " << fname << endl;
    return 0;
  }
  for (int r = 0; r < im.rows; r++)
  {
    ouF.write(reinterpret_cast<const char*>(im.ptr(r)), im.cols*im.elemSize());
  }
  ouF.close();
  return 1;
}

2、用matlab读出二进制文件中的数据

在用matlab来读数据的时候,你必须知道Mat的宽度,高度,通道数,单个通道元素的类型

以三通道,UCHAR为例,读取数据,显示数据。


C++程序,用于调用abWrite函数。

Mat orgIm = imread("im.jpeg");
abWrite(orgIm, "./orgIm_8UC3.dat");

Matlab程序,读出orgIm_8UC3.dat的数据,并调整为RGB数据显示。

width  = 321; % 这个地方你要指定为你自己的矩阵的宽度
height = 481; % 这里也要指定为你自己的矩阵的高度
channels = 3; % 通道数
fs = fopen('orgIm_8UC3.dat', 'rb');
db = fread(fs, 'uint8'); % 注意,这里用的是unsigned int8
fclose(fs);

ou = reshape(db, channels*height, width); % 调整显示格式

im(:,:,1) = ou(3:3:end, :)'; % R通道
im(:,:,2) = ou(2:3:end, :)'; % G通道
im(:,:,3) = ou(1:3:end, :)'; % B通道
figure; imshow(uint8(im)) % 一定要记得转换为uint8


我的用的测试图像:

使用C++将OpenCV中Mat的数据写下二进制文件,用Matlab读出


执行matlab后的显示图像:

使用C++将OpenCV中Mat的数据写下二进制文件,用Matlab读出


这个实验说明,abWrite很大可能是没有问题的,如果你愿意测试,赶紧写个代码测试下吧。测试有问题,欢迎评论,我会尽快解决。