opencv的C++实现将图片二值化后提取像素信息保存至txt文档中,再从txt文档中读取图片像素信息恢复成灰度图并保存

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

int main()
{
//将图片二值化后提取像素信息保存至txt文档中

string filename = "path.png";//图片路径
Mat src = imread(filename); 
cvtColor(src, src, CV_BGR2GRAY);
imshow("原图", src);
fstream file("path.txt", ios::out);//保存像素信息的txt文本路径
stringstream ss;
string data0;
for (int nrows = 0; nrows < src.rows; nrows++) 
{
	for (int ncols = 0; ncols < src.cols; ncols++) 
	{
		int gray = src.at<uchar>(nrows, ncols);
		ss << hex << gray;
		ss >> data0;
        ss.clear();
		file << data0 << " ";
		
	}
	file << endl;

}
file.close();				
//从txt文档中读取图片像素信息恢复成灰度图并保存
fstream fileread;
fileread.open("path.txt");//保存像素信息的txt文本路径
Mat dataread = Mat::zeros(src.rows, src.cols, CV_8UC1);
string data;
uchar idata;
int data1;
for (int i = 0; i < src.rows; i++)
{
	for (int j = 0; j < src.cols; j++)
	{
		fileread >> data;
		ss << data;
		ss >>data1;
		ss.clear();
		idata = (uchar)data1;
		dataread.at<uchar>(i, j)= idata;
	}
}
fileread.close();			
imshow("重构", dataread);
imwrite("path.jpg", dataread);//保存从txt文本中重新生成的灰度图的路径

waitKey(0);
return 0;

}

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值