0

I saved a large matrix in OpenCV using simply std::ofstream, like so:

Mat someData;
std::ofstream fout("someFile");
fout << someData;

It stores the whole matrix in a file with , as the column separator and ; as the row separator.

Is it possible to extract this data back into an OpenCV matrix again? How? Trying to do the converse with std::ifstream throws a "cannot bind" error.

Speed/efficiency/elegance is not a concern.

a-Jays
  • 1,182
  • 9
  • 20

1 Answers1

1

It's possible to load it from the file you wrote. You can first load the whole file into a long string. Then follow this thread How to split a string in C++? to first split the whole string based on ;, i.e. each of which stands for a row. After this, split it again based on ,.


PS: it's much easier if you use cv::FileStorage while I/O matrices:

// write:
cv::Mat m = ...;
cv::FileStorage fs("myfile.txt", cv::FileStorage::WRITE);
fs << "mat" << m;
fs.release();

// read:
cv::Mat m2;
cv::FileStorage fs2("myfile.txt", cv::FileStorage::READ);
fs2["mat"] >> m2;
fs2.release();
Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
  • Yes I know about `FileStorage` but I made the mistake of not using it. Now I'm stuck. – a-Jays Sep 26 '14 at 06:34
  • How would you say is it possible to do it, given the situation? – a-Jays Sep 26 '14 at 06:52
  • And then convert the parsed substrings into floats/ints? That's a long procedure! But that would work. Meanwhile, I removed the `,`s and the `;`s using usual find+replace and then read the values (using `ifstream`) into `myMat.at(i,j)` inside a double loop. Does the job. Thank you. – a-Jays Sep 26 '14 at 09:16