Error reading text file into Mat in OpenCV [closed]
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;
}
Does this code run? Or does it crash? Did you try to print out "m" to see if the doubles are being correctly read?
I've debugged this code around while loop. It doesn't go inside this while loop
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.Thank-you.