What is the most elegant and efficient way to convert a nested std::vector
of std::vector
s to cv::Mat
? The nested structure is holding an array, i.e. all the inner std::vector
s 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?
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 matrixMat(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
.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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With