opencv mat 二进制序列化
可以保存所有的mat类型
#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
bool Mat_read_binary(std::string filename,cv::Mat &img_vec)
{
int channl(0);
int rows(0);
int cols(0);
short type(0);
short em_size(0);
std::ifstream fin(filename, std::ios::binary);
fin.read((char *)&channl, 1);
fin.read((char *)&type, 1);
fin.read((char *)&em_size, 2);
fin.read((char *)&cols, 4);
fin.read((char *)&rows, 4);
printf("filename:cols=%s,%d,type=%d,em_size=%d,rows=%d,channels=%d\n", filename.c_str(), cols, type, em_size, rows, channl);
img_vec = cv::Mat(rows, cols, type);
fin.read((char *)&img_vec.data[0], rows * cols * em_size);
fin.close();
return true;
}
bool Mat_save_by_binary(std::string filename,cv::Mat &image) //单个写入
{
int channl = image.channels();
int rows = image.rows;
int cols = image.cols;
short em_size = image.elemSize();
short type = image.type();
std::fstream file(filename, std::ios::out | std::ios::binary); // | ios::app
file.write(reinterpret_cast<char *>(&channl), 1);
file.write(reinterpret_cast<char *>(&type), 1);
file.write(reinterpret_cast<char *>(&em_size), 2);
file.write(reinterpret_cast<char *>(&cols), 4);
file.write(reinterpret_cast<char *>(&rows), 4);
printf("SAVE:cols=%d,type=%d,em_size=%d,rows=%d,channels=%d\n", cols, type, em_size, rows, channl);
file.write(reinterpret_cast<char *>(image.data), em_size * cols * rows);
file.close();
return true;
}
|