'append row to cv::Mat by push_back std::vector

I have a std::vector of the same data type as a cv::Mat. The number of elements in the vector is the same as the number of columns in the matrix. However, when I cv::Mat::push_back the vector it fails with:

... Pushed vector length is not equal to matrix row length in function 'push_back'

And here's a minimal example:

#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>

int
main()
{
  cv::Mat m (2, 3, CV_32FC1);
  std::cout << "m has " << m.rows << " rows and " << m.cols << " cols\n"
            << m << "\n";

  std::vector<float> v {1,2,3};
  std::cout << "v has " << v.size() << " elements\n";

  m.push_back(v);

  return 0;
}

which returns:

m has 2 rows and 3 cols
[0, 0, 0;
 0, 0, 0]
v has 3 elements
terminate called after throwing an instance of 'cv::Exception'
  what():  OpenCV(4.5.1) ../modules/core/src/matrix.cpp:1078: error: (-209:Sizes of input arguments do not match) Pushed vector length is not equal to matrix row length in function 'push_back'

Aborted

I know I can do something like:

m.push_back(cv::Mat (1, v.size(), CV_32FC1, v.data()));

but I was hoping to make it simpler. What am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source