opencv输出图像数据到txt文件

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)结果



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值