1 | initial version |
I know this is an old question, but I had to do this recently... There's a great/easy answer here which makes use of the boost serialization library:
http://stackoverflow.com/a/21444792/1072039
2 | No.2 Revision |
I know this is an old question, but I had to do this recently... There's a great/easy answer here on stackoverflow, which makes I make use of the boost serialization library:in the below snippet. serializeMat() saves to a binary file and deserializeMat() loads from the same file.
http://stackoverflow.com/a/21444792/1072039Note that, by default (using binary_xarchive), the files are not platform-independant. Use the equivalent text_xarchive instead if you require multi-platform-compatibility of the saved files.
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
void serializeMat(const string& filename, Mat& mat) {
ofstream ofs(filename.c_str());
boost::archive::binary_oarchive oa(ofs);
serialize(oa, mat, 0);
}
void deserializeMat(Mat& mat, const string& filename) {
std::ifstream ifs(filename.c_str());
boost::archive::binary_iarchive ia(ifs);
serialize(ia, mat, 0);
}
// http://stackoverflow.com/a/21444792/1072039
template<class Archive>
void serialize(Archive &ar, cv::Mat& mat, const unsigned int)
{
int cols, rows, type;
bool continuous;
if (Archive::is_saving::value) {
cols = mat.cols; rows = mat.rows; type = mat.type();
continuous = mat.isContinuous();
}
ar & cols & rows & type & continuous;
if (Archive::is_loading::value)
mat.create(rows, cols, type);
if (continuous) {
const unsigned int data_size = rows * cols * mat.elemSize();
ar & boost::serialization::make_array(mat.ptr(), data_size);
} else {
const unsigned int row_size = cols*mat.elemSize();
for (int i = 0; i < rows; i++) {
ar & boost::serialization::make_array(mat.ptr(i), row_size);
}
}
}