Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opencv store to database

Is there a way to save opencv objects to database (like oracle, mysql a.s.o) instead of xml file ?

CvSave is like a blackbox.

like image 662
Jayka Avatar asked Jul 06 '10 21:07

Jayka


1 Answers

Your question is a good one. Saving to XML requires much more space on disc and loads slower. I had the problem myself and wrote a short code which saves Mat to disc, You change it to save other objects.

// Save matrix to binary file
int saveMat( const string& filename, const Mat& M){
    if (M.empty()){
       return 0;
    }
    ofstream out(filename.c_str(), ios::out|ios::binary);
    if (!out)
       return 0;

    int cols = M.cols;
    int rows = M.rows;
    int chan = M.channels();
    int eSiz = (M.dataend-M.datastart)/(cols*rows*chan);

    // Write header
    out.write((char*)&cols,sizeof(cols));
    out.write((char*)&rows,sizeof(rows));
    out.write((char*)&chan,sizeof(chan));
    out.write((char*)&eSiz,sizeof(eSiz));

    // Write data.
    if (M.isContinuous()){
       out.write((char *)M.data,cols*rows*chan*eSiz);
    }
    else{
       return 0;
    }
    out.close();
    return 1;
}

/****************************************************************************/
// Read matrix from binary file
int readMat( const string& filename, Mat& M){
    ifstream in(filename.c_str(), ios::in|ios::binary);
    if (!in){
       M = NULL_MATRIX;
       return 0;
    }
    int cols;
    int rows;
    int chan;
    int eSiz;

    // Read header
    in.read((char*)&cols,sizeof(cols));
    in.read((char*)&rows,sizeof(rows));
    in.read((char*)&chan,sizeof(chan));
    in.read((char*)&eSiz,sizeof(eSiz));

    // Determine type of the matrix 
    int type = 0;
    switch (eSiz){
    case sizeof(char):
         type = CV_8UC(chan);
         break;
    case sizeof(float):
         type = CV_32FC(chan);
         break;
    case sizeof(double):
         type = CV_64FC(chan);
         break;
    }

    // Alocate Matrix.
    M = Mat(rows,cols,type,Scalar(1));  

    // Read data.
    if (M.isContinuous()){
       in.read((char *)M.data,cols*rows*chan*eSiz);
    }
    else{
       return 0;
    }
    in.close();
    return 1;
}
like image 67
DanielHsH Avatar answered Sep 21 '22 11:09

DanielHsH