OpenCV 图像保存为二进制文件及其复原(2)

	**数据的访问方式不同,效率也不同,今天介绍一种更为高效的方式,直接上代码。**
	//图像数据存储为二进制流文件 src:源图像 datName:欲保存的文件名
	void img2dat(Mat src, string datName)
	{
		//把mat 转换 为 IplImage 原因是这种图像格式数据访问更为高效
		IplImage img = src;
		string fileName = datName + ".dat";
		//图像宽、高、通道、深度 有时我们需要放置一些头信息,因此学会这一点也是很重要的
		int height = img.height, width = img.width, depth = img.depth, channel = img.nChannels, dataSize = img.imageSize, widthStep = img.widthStep;
		//创建dat文件,其中前5*4字节为图像宽、高、通道、深度信息
		ofstream outFile(fileName, ios::out | ios::binary);
		outFile.write((char*)&width, sizeof(width));
		outFile.write((char*)&height, sizeof(height));
		outFile.write((char*)&depth, sizeof(depth));
		outFile.write((char*)&channel, sizeof(channel));
		outFile.write((char*)&dataSize, sizeof(dataSize));
		outFile.write((char*)&widthStep, sizeof(widthStep));
		//写入图像像素到dat文件
		outFile.write((char*)img.imageData, dataSize);
		outFile.close();
	}
	//二进制文件复原为图像,前提是你要对Img2dat的过程及数据特点及其熟悉
	void dat2img(Mat& dest, string datName)
	{
		string fileName = datName + ".dat";
		//读取二进制流文件,将其保存为图像 与上面对应,读取头信息
		int head[6];
		//第一步,取出头信息(图像宽、高、通道、深度、图像指针区域大小)
		ifstream fp(fileName, ios::binary);
		fp.read((char*)head, 6 * sizeof(int));
		int width, height, depth, channels, dataSize, widthStep;;
		width = head[0];
		height = head[1];
		depth = head[2];
		channels = head[3];
		dataSize = head[4];
		widthStep = head[5];

		//声明图像
		CvSize imgSize = cvSize(width, height);
		IplImage* img = cvCreateImage(imgSize, depth, channels);

		//把文件中的数据,读入到图像的指针区域中
		fp.read(img->imageData, dataSize);
		fp.close();
		//Ipimage 转为 cvMat
		dest = cvarrToMat(img, false);
	}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忘·月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值