opencv输出图像数据到txt文件
1、输出二值图像数据到txt文件
(1)代码如下:
#include <opencv2/opencv.hpp >
#include <iostream>
#include <fstream>
using namespace std;
using namespace cv;
int main()
{
//const char* filename = "42.jpg"; //图片名
string filename="42.jpg";
Mat src = imread(filename); //载入灰度图
imshow("原图",src);
Mat gray;
cvtColor(src,gray,CV_RGB2GRAY);//彩色转化为灰度
imshow("灰度图",gray);
Mat bin;
threshold(gray,bin,100,255,CV_THRESH_BINARY); //图像二值化
imshow("二值图",bin);
cout<<bin;
ofstream file("test.txt", ios::out);//打开一个文件,等同于file.open("test.txt", ios::out);
for(int nrow = 0; nrow < bin.rows; nrow++) //行遍历
{
for(int ncol = 0; ncol < bin.cols; ncol++) //列遍历
{
uchar val = bin.at<uchar>(nrow,ncol); //获得(x,y)处像素值
if (val==255)
{
val=1;
}
else
{
val=0;
}
file <<int(val) ; //将像素值转化为整数后写入文件
cout<<int(val);
}
cout << endl ; //打印一行后进行换行
file << endl ;
}
file.close(); //关闭文件
cout << endl;
waitKey(0);
return 0;
}
(2)结果
在当前工程目录下生成了test.txt文件,内容如下:
2、输出彩色图像数据到txt文件
(1)代码
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
using namespace std;
using namespace cv;
int main()
{
//const char* filename = "42.jpg"; //图片名
string filename="42.jpg";
Mat src = imread(filename); //载入灰度图
imshow("原图",src);
fstream file("test.txt",ios::out); //打开一个文件
for( int nrows = 0; nrows < src.rows; nrows++) //行遍历
{
for( int ncols = 0; ncols < src.cols; ncols++) //列遍历
{
Vec3i RGB_v = src.at<Vec3b>(nrows,ncols); //用Vec3b也行,获得(x,y)处的像素值
cout << "("<<RGB_v.val[0]<<"," <<RGB_v.val[1]<<"," <<RGB_v.val[2]<<")"; //打印数据到控制台
file << "("<<RGB_v.val[0]<<"," <<RGB_v.val[1]<<"," <<RGB_v.val[2]<<")"; //输出数据到test.txt文件
}
cout << endl; //输出一行像素值后换行
file << endl;
}
file.close(); //关闭文件
cout << endl;
waitKey(0);
return 0;
}
(2)结果