opencv将图像数据写入二进制(.dat)文件

在图像处理的过程中,有些时候需要以二进制形式从dat文件读取数据或者将数据写入dat文件,特别是在matlab当中。

1、写入二进制文件

opencv中可以进行如下操作,将图像写入二进制文件:

//图像写入二进制(.dat)文件
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/ml/ml.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;

#include <iostream>
#include <fstream>
using namespace std;

//
const string filename = "test.dat";
const string picname = "cat.jpg";
//

int main(int argc, char **argv)
{
	//打开文件
	ofstream outfile;
	outfile.open(filename.c_str(), ios::binary);
	if (!outfile)
	{
		cerr << "failed to open the file : " << filename << endl;
		return -1;
	}

	//打开图像
	Mat srcImg = imread(picname);
	if (srcImg.empty())
	{
		cerr << "failed to open the file : " << picname << endl;
		return -1;
	}

	//写入二进制文件
	for (int r = 0; r < srcImg.rows; r++)
		outfile.write(reinterpret_cast<const char*>(srcImg.ptr(r)), srcImg.cols*srcImg.elemSize());
	//outfile<<endl;
	cout<<"write to file ok!"<<endl;

	return 0;
}

测试用的图像:


得到的数据文件:



2、读取二进制文件

matlab中可以进行如下操作,将图像数据从二进制dat文件中读取出来并显示:

width  = 120; % 原图像宽度
height = 120; % 原图像高度
channels = 3; % 原图像通道数
% 打开并读取文件
file = fopen('test.dat', 'rb');
cont = fread(file, 'uint8');
fclose(file);
% 转化并显示图像
data = reshape(cont, channels*height, width); % 调整显示格式
im(:,:,1) = data(3:3:end, :)'; % R通道
im(:,:,2) = data(2:3:end, :)'; % G通道
im(:,:,3) = data(1:3:end, :)'; % B通道
figure; imshow(uint8(im))

matlab显示结果:



  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值