2015-08-18 34 views
2

我目前正在嘗試序列化和反序列化openCV Mat,以便我可以使用Boost將客戶端的幀發送到服務器。我遇到的問題是,當我反序列化圖像時,它會給出不同顏色的重疊圖像。我不知道爲什麼會發生這種情況。任何幫助將非常感激。對不起,我無法發佈圖片,因爲我沒有足夠的徽章。主cv :: Mat的序列化給出奇怪的結果

#include "serialization.h" 

using namespace std; 
using namespace cv; 
using namespace boost; 

Mat frame; 

void saveMat(Mat& m, string filename); 
void loadMat(Mat& m, string filename); 

int main(int argc, const char * argv[]) { 
    // insert code here... 

    CvCapture* capture = cvCaptureFromCAM(CV_CAP_ANY); //Capture using  any camera connected to your system 
    cvNamedWindow("serialization", 2); //Create window 

    while(1) { 
     frame = cvQueryFrame(capture); 

     saveMat(frame, "archive.bin"); 
     cv::Mat frame2; 
     loadMat(frame2, "archive.bin"); 
     IplImage tmp = frame2; 

     cvShowImage("serialization", &tmp); 
    } 

    return 0; 
} 

void saveMat(Mat& m, string filename) { 
    ofstream ofs(filename.c_str()); 
    archive::binary_oarchive oa(ofs); 
    oa << m; 
} 

void loadMat(Mat& m, string filename) { 
    ifstream ifs(filename.c_str()); 
    archive::binary_iarchive ia(ifs); 
    ia >> m; 
} 
    enter code here 

回答

0

爲CV的自定義序列

頭文件::墊

#ifndef cv__Mat_Serialization_serialization_h 
    #define cv__Mat_Serialization_serialization_h 

    BOOST_SERIALIZATION_SPLIT_FREE(cv::Mat) 
    namespace boost { 
     namespace serialization { 
      template<class Archive> 
      void save(Archive & ar, const cv::Mat& mat, const unsigned int version) { 
       size_t elementSize = mat.elemSize(); 
       size_t elementType = mat.type(); 

       ar << mat.cols; 
       ar << mat.rows; 
       ar << elementSize; 
       ar << elementType; 

       for(int y = 0; y < mat.rows*mat.cols*(elementSize); y++) { 
        ar << mat.data[y]; 
       } 


      } 
      template<class Archive> 
      void load(Archive & ar, cv::Mat& mat, const unsigned int version) { 
       int cols = 0; 
       int rows = 0; 
       size_t elementSize; 
       size_t elementType; 

       ar >> cols; 
       ar >> rows; 
       ar >> elementSize; 
       ar >> elementType; 

       mat.create(rows,cols,static_cast<int>(elementType)); 

       for(int y = 0; y < mat.rows*mat.cols*(elementSize); y++) { 
        ar >> mat.data[y]; 
       } 
      } 
     } 
    } 

    #endif 

代碼中,我用你確切的代碼,添加到waitKey(...)顯示輸出,沒問題:

enter image description here

您應該使用盡管如此,在for循環中代替了int而代替了。而你可以減少變量壽命位:

while(1) { 
    { 
     Mat frame = cvQueryFrame(capture); 

     saveMat(frame, "archive.bin"); 
    } 

    { 
     cv::Mat frame2; 
     loadMat(frame2, "archive.bin"); 
     IplImage tmp = frame2; 

     cvShowImage("serialization", &tmp); 
    } 

    if(waitKey(30) == 'q') break; 
} 

如果你有這個問題,我想,你捕捉源可能有不同的圖像表示,你可能要像做

cvtColor(frame2, frame3, CV_BGR2RGB); 

等等。

+0

非常感謝,原來我在調用saveMat函數之前添加了這個。 –

+0

cvtColor(frame,frame,CV_BGR2BGRA); –

+0

你知道這是爲什麼嗎?如果有任何問題,我正在使用MacBook Pro的網絡攝像頭。 –