Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

opencv

mat

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;
    }
like image 837
posha Avatar asked Dec 16 '22 05:12

posha


1 Answers

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;
like image 125
berak Avatar answered Dec 29 '22 14:12

berak