How to write a Float Mat to a file in OpenCV
c++, file-io, floating-point, mat, opencv
Solution
Using pure OpenCV API calls:
// Declare what you need
cv::FileStorage file("some_name.ext", cv::FileStorage::WRITE);
cv::Mat someMatrixOfAnyType;
// Write to file!
file << "matName" << someMatrixOfAnyType;
// Close the file and release all the memory buffers
file.release();
The file extension can be xml or yml. In both cases you get a small header that you can easily remove/parse, then you have access to the data in a floating point format. I used this approach successfully (with .yml files) to get data into MATLAB and Matplotlib.
To get the data:
- open the file with any editor
- then suppress all the text and numbers, except the content of the data tag (i.e., the pixel values).
- When done, save your file with a .txt or .csv extension and open it with MATLAB (drag-and-drop works).
Voilà. You may have to reshape the resulting matrix on the MATLAB command line if it didn't guess the image size correctly.
Problem
I have a matrix, `Mat B(480,640,CV_32FC1);` containing floating-point values. I want to write this matrix to a file which could be opened in Notepad or Microsoft Word or Excel to see the values inside and for storage, but the imwrite function can save 8-bit or 16-bit images only... Could this be done? If yes, how?