1. 程式人生 > >實用的OpenCV程式碼片段(1)-- 利用Boost將cv::Mat序列化

實用的OpenCV程式碼片段(1)-- 利用Boost將cv::Mat序列化

如何將cv::Mat型別序列化

使用Boost的serialization庫。
官方說明在這裡

下面就是採用的非入侵方法給Mat增加序列化功能的程式碼

#include <opencv2/opencv.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
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);