Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a std::vector<std::vector <double> > representing a 2D array to cv::Mat

What is the most elegant and efficient way to convert a nested std::vector of std::vectors to cv::Mat? The nested structure is holding an array, i.e. all the inner std::vectors have the same size and represent matrix rows. I don't mind the data being copied from one to another.

I know that a single, non-nested std::vector is very easy, there is a constructor:

std::vector <double> myvec;
cv::Mat mymat;

// fill myvec
bool copy = true;

myMat = cv::Mat(myvec, copy);

What about the nested vector?

like image 620
penelope Avatar asked Jun 05 '12 13:06

penelope


2 Answers

My variant (requires OpenCV 2.4):

int size = 5;
vector<vector<double> > w(size);
for(int i = 0; i < size; ++i)
{
    w[i].resize(size);
    for(int j = 0; j < size; ++j)
        w[i][j] = (i+1) * 10 + j;
}

Mat m(size, size, CV_64F);
for(int i = 0; i < w.size(); ++i)
    m.row(i) = Mat(w[i]).t();

cout << m << endl;

Outputs:

[10, 11, 12, 13, 14;
  20, 21, 22, 23, 24;
  30, 31, 32, 33, 34;
  40, 41, 42, 43, 44;
  50, 51, 52, 53, 54]

Explanation of m.row(i) = Mat(w[i]).t():

  • m.row(i) sets the ROI, it points to original matrix
  • Mat(w[i]) wraps vector without data copying
  • .t() creates "matrix expression" - no data copying performed
  • = evaluates matrix expression but because vector is wrapped into the (size x 1) continuous matrix it is evaluated without real transpose with a single call to memcpy.
like image 73
Andrey Kamaev Avatar answered Nov 10 '22 01:11

Andrey Kamaev


This is a way to do it:

std::vector<double> row1;
row1.push_back(1.0); row1.push_back(2.0); row1.push_back(3.0);

std::vector<double> row2;
row2.push_back(4.0); row2.push_back(5.0); row2.push_back(6.0);

std::vector<std::vector<double> > vector_of_rows;
vector_of_rows.push_back(row1);
vector_of_rows.push_back(row2);

// make sure the size of of row1 and row2 are the same, else you'll have serious problems!
cv::Mat my_mat(vector_of_rows.size(), row1.size(), CV_64F);

for (size_t i = 0; i < vector_of_rows.size(); i++)
{   
    for (size_t j = 0; j < row1.size(); j++)
    {   
        my_mat.at<double>(i,j) = vector_of_rows[i][j];
    }   
}   

std::cout << my_mat << std::endl;

Outputs:

[1, 2, 3;
  4, 5, 6]

I tried another approach using the constructor of Mat and the push_back() method but without success, maybe you can figure it out. Good luck!

like image 29
karlphillip Avatar answered Nov 10 '22 02:11

karlphillip