Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

This works for me for reading .txt files. Please include the relevant header files.

//To read data from a text file. 
//filename is the name of the text file
//rows and cols show dimensions of the matrix written in the text file

#include"stdafx.h"
#include<fstream>

using namespace std;
using namespace cv;

Mat ReadMatFromTxt(string filename, int rows,int cols)
{
    double m;
    Mat out = Mat::zeros(rows, cols, CV_64FC1);//Matrix to store values

    ifstream fileStream(filename);
    int cnt = 0;//index starts from 0
    while (fileStream >> m)
    {
        int temprow = cnt / cols;
        int tempcol = cnt % cols;
        out.at<double>(temprow, tempcol) = m;
        cnt++;
    }
    return out;

However, you must know the dimensions of the matrix beforehand. Any improvement is appreciated.

This works for me for reading .txt files. Please include the relevant header files.

//To read data from a text file. 
//filename is the name of the text file
//rows and cols show dimensions of the matrix written in the text file

#include"stdafx.h"
#include<fstream>

using namespace std;
using namespace cv;

Mat ReadMatFromTxt(string filename, int rows,int cols)
{
    double m;
    Mat out = Mat::zeros(rows, cols, CV_64FC1);//Matrix to store values

    ifstream fileStream(filename);
    int cnt = 0;//index starts from 0
    while (fileStream >> m)
    {
        int temprow = cnt / cols;
        int tempcol = cnt % cols;
        out.at<double>(temprow, tempcol) = m;
        cnt++;
    }
    return out;
}

However, you must know the dimensions of the matrix beforehand. Any improvement is appreciated.