#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;
}
文章来源: https://blog.csdn.net/weixin_44734885/article/details/89789469