实用的OpenCV代码片段(1)-- 利用Boost将cv::Mat序列化

如何将cv::Mat类型序列化

使用Boost的serialization库。
官方说明在这里

这段代码的来源在这里:http://stackoverflow.com/questions/4170745/serializing-opencv-mat-vec3f

下面就是采用的非入侵方法给Mat增加序列化功能的代码

#include 
#include 
#include 
using namespace cv;

namespace boost {
    namespace serialization {
        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);
                }
            }

        }
    }
}

使用:

Mat object_color = imread("img.JPG");
imshow("origin", object_color);
// create and open a character archive for output
std::ofstream ofs("test.txt");

// save data to archive
{
    boost::archive::text_oarchive oa(ofs);
    // write class instance to archive
    oa << object_color;
}
ofs.close();
Mat loaded_s;
{
    // archive and stream closed when destructors are called
    std::ifstream ifs("test.txt");
    boost::archive::text_iarchive ia(ifs);
    // read class state from archive

    ia >> loaded_s;
}

imshow("loaded",loaded_s);
waitKey(0);

你可能感兴趣的:(opencv学习,C++,代码片段,opencv,boost,序列化)