Saving OpenCV matrices to disc and loading them

Recently I needed to save some matrices I had generated with OpenCV and C++. This snippet of code shows you how you can do this this and then open the files to retrieve the matrices.  You can save the files as either the .yml or .xml format. In the example below, “trainData” and “trainLabels” are the two matrices I want to save:

cv::FileStorage file("tag_data.yml", cv::FileStorage::WRITE);

file << "data" << trainData;
file << "classes" << trainLabels;
file.release();

// later (in another program when you want to get the stored matrices)

cv::Mat trainDataCopy, trainLabelsCopy;

cv::FileStorage file("tag_data.yml", cv::FileStorage::READ);

file["data"] >> trainDataCopy;
file["classes"] >> trainLabelsCopy;

file.release();

Done. You should now be able to use both matrices.

The following two tabs change content below.
Computational biology PhD candidate at the Australian National University. I love writing (both articles and software), learning more about the world around us, and beekeeping. I also write for BioSky.co

Latest posts by Jack Simpson (see all)

Comments are closed.