opencv mat 二进制序列化

opencv mat 二进制序列化

可以保存所有的mat类型

#include 
#include 
#include 
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(&channl), 1);
    file.write(reinterpret_cast(&type), 1);
    file.write(reinterpret_cast(&em_size), 2);
    file.write(reinterpret_cast(&cols), 4);
    file.write(reinterpret_cast(&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(image.data), em_size * cols * rows);
    file.close();
    return true;
}

你可能感兴趣的:(杂项,opencv,c++)