简体   繁体   中英

How to convert a 3D vector to a cv::Mat

I am trying to fill up an OpenCV Mat (float) from a 3D vector of floats (vGraph1). However, the resulting OpenCV Mat (test) is not correctly filled, ie only the first column is filled with correct values while the rest are junk values (-4.32e+08). I confirmed the error by writting the Mat to a text file. Am I doing something wrong? kindly advice. Thanks.

int nStates = 9; const int rows = 10; const int cols = 10;
vector < vector < vector<float> > > vGraph1;
 for(int iii = 0; iii < rows; iii++){
     vGraph1.push_back(vector<vector<float> >());
     for(int jjj = 0; jjj < cols; jjj++){
         vGraph1[iii].push_back(vector<float>());
         for(int kkk = 0; kkk < nStates; kkk++){ 
             vGraph1[iii][jjj].push_back(rand());
             cout <<  vGraph1[iii][jjj][kkk] << " ";
         }
         cout << endl;
      }
  }
 cout << "OpenCV Mat \n" << endl;
 Mat test(rows, cols, CV_MAKE_TYPE(CV_32F, nStates));
 for(int iii = 0; iii < rows; iii++){
     float *ptest = test.ptr<float>(iii);
     for( int jjj = 0; jjj < cols; jjj++){
         for (int kkk = 0; kkk < nStates; kkk++){
             ptest[kkk] = vGraph1[iii][jjj][kkk];
             cout << ptest[kkk] << " ";
         }
         cout << endl;
     }

 }
 FileStorage Save("Mat.txt", FileStorage::WRITE);
 Save << "Node" << test;
 Save.release();

I manage to get the following working solution; I hope it is correct?

int nStates = 9; const int rows = 10; const int cols = 10;
vector < vector < vector<float> > > vGraph1;
 for(int iii = 0; iii < rows; iii++){
     vGraph1.push_back(vector<vector<float> >());
     for(int jjj = 0; jjj < cols; jjj++){
         vGraph1[iii].push_back(vector<float>());
         for(int kkk = 0; kkk < nStates; kkk++){ 
             vGraph1[iii][jjj].push_back(rand());
             cout <<  vGraph1[iii][jjj][kkk] << " ";
         }
         cout << endl;
      }
  }
 cout << "OpenCV Mat \n" << endl;
 Mat test(rows, cols, CV_MAKE_TYPE(CV_32F, nStates));
 for(int iii = 0; iii < rows; iii++){
     float *ptest = test.ptr<float>(iii);
     for( int jjj = 0; jjj < cols; jjj++){
         for (int kkk = 0; kkk < nStates; kkk++){
             ptest[nStates*jjj + kkk] = vGraph1[iii][jjj][kkk];
             cout << ptest[nStates*jjj+kkk] << " ";
         }
         cout << endl;
     }

 }

 FileStorage Save("Mat.txt", FileStorage::WRITE);
 Save << "Node" << test;
 Save.release();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM