Saturday, March 9, 2013

Reading and Writing cv::Mat in OpenCV in C++

In C++ api for OpenCV, you often come across writing and reading matrices as text files (analogous to saving .mat files in MATLAB/Octave). This is a simple way of doing it. You could even save multiple matrices in a single .xml/.yaml file. 
Note: You could write matrices using C++ and use Python API (which is very useful for Prototyping as development on Python is faster than C++ and many Machine Learning APIs are available for use).

However, I couldn't find ways to read more than 1 matrix which was written to file and being read using Python API. 

Matrix types in using imshow and imwrite

I have never paid attention to trivial functions in OpenCV like

while using matrix types.

It turns out that only 3 Channel or Single Channel images can be saved using imwrite (in specific 8bit images, and 16 bit images of PNG, JPEG 2000 and TIFF type). Click here for more details.

For example, the following image has values from 0 to 1 (floating type), but when you write it to disk, all you can see is "NOTHING". That is so because, imwrite only writes 8 bit 3 channel or 1 channel images. Also when you do an imread on the same image, you get a 8bit image. Its not the same CV_32F image that you've written to disk.

Other formats of cv::Mat have to use FileStorage class provided with OpenCV. Using this one can save matrices of type CV_32F.