Ask Your Question
0

Read text file into mat

asked 2016-09-02 02:18:37 -0600

Nbb gravatar image

updated 2016-09-02 02:58:19 -0600

Hi, my text file contains 640 rows 480 columns of floating points. Id like to read them into a matrix and reshape at the end. But the code below only reads a single data per row. Help me edit the stream >> x please. Data separated by commas

example 2.752,2.7521,2.7522,2.7524,2.7528,2.7532,2.7536,2.7542,2.7548,2.7555,2.7562,2.7569,2.7576,2.7583,2.7591,

std::ifstream file("img1.txt");

Mat depthImg;
int rows = 0;
std::string line;
while (std::getline(file, line)) {  

    std::istringstream stream(line);

    //double x;
    //while (stream >> x) {

        //depthImg.push_back(x);
    //}

    while (stream)
    {
        string s;
        if (!std::getline(stream, s, ',')) break;
        depthImg.push_back(std::stof(s));
    }

rows++;
}


// reshape to 2d:
depthImg = depthImg.reshape(1, rows);
edit retag flag offensive close merge delete

Comments

Hi thanks ! the data is saved using matlab. im not sure how to replace commas with white spaces in matlab and I thought it'd be easier to just read it in C++/OpenCV

Nbb gravatar imageNbb ( 2016-09-02 02:44:59 -0600 )edit

see answer below.

berak gravatar imageberak ( 2016-09-02 02:49:59 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
2

answered 2016-09-02 02:48:50 -0600

berak gravatar image

updated 2016-09-02 02:53:46 -0600

currently, your code does not handle the seperating commas correctly, also, push_back() produces a single row Mat.

try like this:

std::ifstream file("img1.txt");

Mat depthImg;
int rows = 0;
std::string line;
while (std::getline(file, line)) {  

    std::istringstream stream(line);

    char sep; //comma!
    double x;
    // read *both* a number and a comma:
    while (stream >> x && stream >> sep) {

        depthImg.push_back(x);
    }
    rows ++;
} 

// reshape to 2d:
depthImg = depthImg.reshape(1,rows);
edit flag offensive delete link more

Comments

1

Great thanks ! I also found another solution (edited my post) to read the data as a string and convert the numbers back to float but I still gotta use the reshape function as the matrix is indeed a single row as you have pointed out.

Nbb gravatar imageNbb ( 2016-09-02 02:59:30 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2016-09-02 02:18:37 -0600

Seen: 4,019 times

Last updated: Sep 02 '16