您的位置:首页 > 编程语言 > C语言/C++

C++将矩阵存到.txt文件, 使用 FILE 或 ofstream

2016-05-02 09:15 405 查看
在C/C++中常常需要查看中间结果,比如:某一个矩阵中的数据的数值情况,在这种情况下常将该数值矩阵存成 .txt文件再查看。比如:

#include<iostream>

#include<stdio.h>

#include"opencv2/highgui/highgui.hpp"

#include"opencv2/imgproc/imgproc.hpp"

#include"opencv2/core/core.hpp"

int main(){

int i, j ;

cv::Mat my_mat( 20, 20, CV_32FC2, cv::Scalar::all(0) ) ;

FILE *fp ;

fp = fopen( "myfile.txt", "w" ) ;

for(i=0; i<my_mat.rows; i++){

for(j=0; j<my_mat.cols; j++){

fprintf(fp, "%3.0f", my_mat.at<float>(i,j) ) ; // the data type should be matched.

// the same as that of my_mat

}

fprintf( fp, "\n" ) ;

}

fclose( fp ) ;

return 1 ;

}

-----------------------------------------------------------------------

fp = fopen( name, mode ) ;

mode : "r" read ,

"w" write, the old contents to be discarded.

"a" append, the old contents to be preserved.

------------------------------------------------------------------------

方法2. 使用 ofstream 对象来保存文件

// 这里假设需要保存图像 img_gray 的灰度值 到文件夹

std::string fileName = "val_img.txt" ;

std::ofstream outfile( fileName.c_str() ) ; // file name and the operation type.

int i, j ;

for( i=0; i<img_gray.rows; i++ ){

for( j=0; j<img_gray.cols; j++ )

outfile << (int) img_gray.at<uchar>(i,j) << " " ; // note the uchar, be changed to int type.

outfile << std::endl ; // a newline after storing all the values of a line of the img

}

outfile.close() ;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: