kcc__
kcc__

Reputation: 1648

Read from Txt file and convert to float mat opencv

I need help with this. I am reading data from the text file. It has 3 column and 100 rows. The data is in (x,y,z) format. I want to combine x and y into one Mat data and Z into another one.

For Z it is easy and I created the float matrix of it. I am reading x and y separately and at the moment i am storing it as float vectors. As in the code below.

char buf[255];
float x, y;
float label;
vector<float> x_coord;
vector<float> y_coord;

Mat class_label(y_coord.size(), 1, CV_32FC1);

if(!inFile.eof())
{
    while (inFile.good())
    {
        inFile.getline(buf, 255);
        string line(buf);
        istringstream iss(line);
        iss >> x;
        x_coord.push_back(x);
        iss >> y;
        x_coord.push_back(y);
        y_coord.push_back(y);
        iss>> label;
        class_label.push_back(label);
    }
    inFile.close();
}

How can i combine x_coord and y_coord to create of Mat of type Mat training_data(y_coord.size(), 2, CV_32FC1, train_data );

That is 2 column by 100 rows. I am doing this but its not working

float train_data[10938][2];

for (int j = 0; j < 2; j++)
{
    for (int i = 0; i < x_coord.size(); i++)
    {
        int index = j + i * x_coord.size();
        train_data[i][j] = x_coord.at(index);  
        //train_data[i][1] = x_coord.at(i);
    }
}

I am really stuck here please help me.

Upvotes: 0

Views: 2930

Answers (1)

vyndor
vyndor

Reputation: 368

You can fill Mat directly without auxiliary array train_data.

for (int j = 0; j < 2; j++)
{
    for (int i = 0; i < x_coord.size(); i++)
    {
        int index = j + i * x_coord.size();
        training_data.at<float>(i, j) = x_coord.at(index);
    }
}

Also you can do the same while reading file. For more info please read Mat::at() documentation.

Upvotes: 2

Related Questions