Home » Saving OpenCV matrices to disc and loading them

Saving OpenCV matrices to disc and loading them

by Jack Simpson

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;

// 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;


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

You may also like