How to read the text file and create Mat object in C++

posha picture posha · Oct 5, 2013 · Viewed 10.9k times · Source

Hi i have being able to write a Mat object in to a text file. As follows,

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( );

In my code in the first 2 lines im printing the row count and the column count to use when im reading it back. But im unable to read the text file and create the Mat Object again.

The following is the code i tried. Not sure whether my code is correct.

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;
    }

Answer

berak picture berak · Oct 5, 2013

it's probably far easier, to use the opencv FileStorage:

// write:
Mat m;
FileStorage fs("myfile.txt",FileStorage::WRITE);
fs << "mat1" << m;

// read:
FileStorage fs("myfile.txt",FileStorage::READ);
fs["mat1"] >> m;