Serializing OpenCV Mat_

前端 未结 7 1224
刺人心
刺人心 2020-11-30 05:29

I\'m working on a robotics research project where I need to serialize 2D matrices of 3D points: basically each pixel is a 3-vector of floats. These pixels are saved in an Op

7条回答
  •  我在风中等你
    2020-11-30 05:42

    The earlier answers are good, but they won't work for non-continuous matrices which arise when you want to serialize regions of interest (among other things). Also, it is unnecessary to serialize elemSize() because this is derived from the type value.

    Here's some code that will work regardless of continuity (with includes/namespace)

    #pragma once
    
    #include 
    #include 
    #include 
    #include 
    
    namespace boost {
    namespace serialization {
    
    template
    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);
            }
        }
    
    }
    
    } // namespace serialization
    } // namespace boost
    

提交回复
热议问题