Home Content 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;
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.

Sign up to my newsletter

Sign up to receive the latest articles straight to your inbox

You may also like

Leave a Comment