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

后端 未结 4 1489
长发绾君心
长发绾君心 2021-01-13 13:45

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

          


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 14:30

    I wrote a method for reading a Mat from an .asc that should work for .txt too.

    Maybe there are more stylish and efficient ways to do that, but this method works and is easy to understand.

    Head

    int Load_From_Path_Text(Mat *pMA_Out, string path)
    

    Variables

    ifstream        IS_File;
    string          ST_Line;
    stringstream    SS_Line;
    unsigned int    rows        = 0;
    unsigned int    cols        = 0;
    unsigned int    y           = 0;
    unsigned int    x           = 0;
    float           F_Value;
    

    Get Size

    IS_File.open(path);
    while(getline(IS_File, ST_Line))
    {
        if(cols == 0)
        {
            SS_Line << ST_Line;
            while(SS_Line >> F_Value)
                cols++;
        }
    
        rows++;
    }
    IS_File.close();
    

    Create Image

    *pMA_Out = Mat(rows, cols, CV_32FC1);
    

    Read Data

    IS_File.open(path);
    while(getline(IS_File, ST_Line))
    {
        SS_Line.clear();
        SS_Line << ST_Line;
        x = 0;
    
        while(SS_Line >> F_Value)
        {
            pMA_Out->at(y, x) = F_Value;
            x++;
        }
    
        y++;
    }
    IS_File.close();
    

    Example

    1 1 1 -2
    1 2 1 0.5
    1 1 3 2.1
    1 1 1 1.5
    

    turns to this (after beeing converted to CV_8UC1 using normalize with CV_MINMAX to be displayed).

提交回复
热议问题