Convert a std::vector<std::vector <double> > representing a 2D array to cv::Mat
c++, image-processing, opencv, stdvector, vector
Solution
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!
Problem
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?