Error reading text file into Mat in OpenCV [closed]

asked 2017-06-05 04:53:48 -0600

updated 2017-06-05 05:14:50 -0600

Hi!

Using OpenCV 3.0 and Visual Studio Professional 2013

I'm facing difficulty in reading a readable text file, generated by MATLAB, in OpenCV. The text file contains signed floating point numbers. One number on each line and total number of lines are 2241 but there is just single column. I want to read this data in to a matrix with just one column and 2241 rows.

But..

The debugger says this next to fstream in watch window: "Error reading characters of string"

*#include <iostream>
*#include <fstream>
*#include "opencv2/imgcodecs.hpp"

*#include "opencv2/highgui.hpp"

using namespace std;
using namespace cv;

void printUsage();
int parseCmdArgs(int argc, char** argv);


Mat ReadMatFromTxt(string filename);

int main(int argc, char* argv[])
{
    string filename = "P:\\svd\\main_CC++\\build\\training_filter.txt";
Mat out = ReadMatFromTxt(filename);

waitKey();
return 0;
}


Mat ReadMatFromTxt(string filename)
{
double m;
ifstream fileStream(filename.c_str(), ifstream::in);
if (!fileStream) {
    string error_message = "No valid input file was given, please check the given filename.";
    CV_Error(Error::StsBadArg, error_message);
}
int rows = 1;

char enterChar;
int numOfLines_InTextFile = 0;
while (fileStream.get(enterChar)) {
    if (enterChar == '\n') {
        ++numOfLines_InTextFile;
    }
}

int cols = numOfLines_InTextFile;

Mat out = Mat::zeros(rows, cols, CV_64FC1);//Matrix to store values

    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++;
}

fileStream.close();
return out;
}
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by sturkmen
close date 2020-09-18 05:05:10.388161

Comments

Does this code run? Or does it crash? Did you try to print out "m" to see if the doubles are being correctly read?

Pedro Batista gravatar imagePedro Batista ( 2017-06-05 06:06:14 -0600 )edit

I've debugged this code around while loop. It doesn't go inside this while loop

Ayesha Siddique gravatar imageAyesha Siddique ( 2017-06-05 07:22:00 -0600 )edit
1

while (fileStream.get(enterChar)) <-- well this walks down the filestream to the end, so your 2nd while loop cannot catch anything. you'll either have to rewind it, or open a new stream.

berak gravatar imageberak ( 2017-06-05 14:16:32 -0600 )edit

Thank-you.

Ayesha Siddique gravatar imageAyesha Siddique ( 2017-06-06 07:08:00 -0600 )edit