As in the title, I have std::vector<cv::Mat> matrices which I want to write/read to/from binary file.
Now, following this answer, all I should do is for writing is:
ofstream fout("matrices.bin", ios::out | ios::binary);
size_t size = matrices.size();
fout.write((char*)&size, sizeof(size));
fout.write((char*)&matrices[0], v.size() * sizeof(cv::Mat));
fout.close();
However, following this answer, writing cv::Mat objects seems a little bit tricky, and in the answer matRead and matWrite do the job. So I wonder if instead of the code above I should do something like:
ofstream fout("matrices.bin", ios::out | ios::binary);
size_t size = matrices.size();
fout.write((char*)&size, sizeof(size));
for(size_t i = 0 ; i < matrices.size() ; i++)
matWrite("matrices.bin", matrices[i]);
However this code doesn't work since matWrite() overwrites matrices.bin at each cycle, so I should append the size of matrices[i] as offset before writing the matrix itself.
What should I do?
UPDATE:
I came up with this solution, rewriting matWrite and matRead with optional arguments for appending matrices during writing and starting to read from a certain point:
void matwrite(const std::string& filename, const cv::Mat& mat, const bool append = false) {
std::ofstream fs;
if(append)
fs.open(filename.c_str(), std::fstream::binary | std::fstream::app);
else
fs.open(filename.c_str(), std::fstream::binary);
//the rest of matwrite is the same...
}
cv::Mat matRead(const std::string& filename, size_t &offset = 0)
{
std::ifstream fs(filename, std::fstream::binary);
fs.seekg(offset);
...
offset += 4 * sizeof(int) + CV_ELEM_SIZE(type) * rows * cols; //update offset //move offset of 4 ints and mat size
return mat;
}
And functions are called with:
//writing:
for(size_t i = 0 ; i<v.size() ; i++)
writemat(filename, v[i], true);
//reading:
size_t offset = 0;
for(size_t i = 0 ; i<size ; i++){ // size = v.size() during writing
cv::Mat mat = matRead(filename, offset);
v.push_back(mat);
}
matAppendwe write one big matrix, which is the concatenation of all the matrices in the vector. However, it's impossible to reconstruct the original vector starting from the obtained.binfile. In few words, we can writestd::vector<cv::Mat>to file as a bigcv::Matbut we cannot obtain thestd::vector<cv::Mat>again.