您好我能够将Mat对象写入文本文件.如下,
std::fstream outputFile;
outputFile.open( "myFile.txt", std::ios::out ) ;
outputFile << des_object.rows << std::endl;
outputFile << des_object.cols << std::endl;
for(int i=0; i<des_object.rows; i++)
{
for(int j=0; j<des_object.cols; j++)
{
outputFile << des_object.at<float>(i,j) << std::endl;
}
}
outputFile.close( );
Run Code Online (Sandbox Code Playgroud)
在我前两行的代码中,我打印行数和列数,以便在读取它时使用.但我无法读取文本文件并再次创建Mat对象.
以下是我试过的代码.不确定我的代码是否正确.
Mat des_object1;
std::ifstream file("myFile.txt");
std::string str;
int rows;
int cols;
int a = 0;
while (std::getline(file, str))
{
int i = 0;
int j = 0;
if(a == 0){
rows = std::stoi( str );
}else if(a == 1){
cols = std::stoi( str );
}else{
for(i; i< rows; i++)
{
for(j; j<cols; j++)
{
des_object1.at<float>(i,j) = ::atof(str.c_str());
break;
}
}
}
++a;
}
Run Code Online (Sandbox Code Playgroud)
ber*_*rak 10
使用opencv FileStorage可能要容易得多:
// write:
Mat m;
FileStorage fs("myfile.txt",FileStorage::WRITE);
fs << "mat1" << m;
// read:
FileStorage fs("myfile.txt",FileStorage::READ);
fs["mat1"] >> m;
Run Code Online (Sandbox Code Playgroud)