10

I am using OpenCV and also want to add some of cool functions from mlpack, which is using Armadillo matrices.

Is there an easy way to convet between cv::Mat and arms::mat?

Thanks!

coatless
  • 20,011
  • 13
  • 69
  • 84
wking
  • 1,293
  • 1
  • 16
  • 27

1 Answers1

15

OpenCV's Mat has a pointer to its data. Armadillo has a constructor that is capable of reading from external data. It's easy to put them together. Remember that Armadillo stores in column-major order, whereas OpenCV uses row-major. I suppose you'll need to add another step for transformation, before or after.

cv::Mat opencv_mat;    //opencv's mat, already transposed.
arma::mat arma_mat( reinterpret_cast<double*>opencv_mat.data, opencv_mat.rows, opencv_mat.cols )

The cv::Mat constructor has a form that accepts pointer to data, and arma::mat has a function for a double* pointer to its data called memptr().

So, if you'd like to convert from arma::mat to cv::Mat, this should work:

cv::Mat opencv_mat( rows, cols, CV_64FC1, arma_mat.memptr() )
mohaghighat
  • 1,293
  • 17
  • 29
a-Jays
  • 1,182
  • 9
  • 20
  • 3
    The code you've posted performs an implicit transposition, so if you have an OpenCV matrix that is row-major (i.e. one observation per row), then the Armadillo matrix you get back is column-major (one observation per column). This is fortunate because mlpack expects column-major data for its algorithms. :) – ryan Nov 17 '14 at 16:43
  • It works! Thank you, a-Jays! But is there a way to convert from arma::mat to cv::Mat? – wking Nov 18 '14 at 02:04
  • 3
    The `cv::Mat` constructor has a form that accepts pointer to data, and `arma::mat` has a function for a `double*` pointer to its data called `memptr()`. So, `cv::Mat opencv_mat( rows, cols, CV_64FC1, arma_mat.memptr() )` should work. Also, consider marking an answer accepted if it solves the problem. – a-Jays Nov 18 '14 at 04:53
  • 1
    Just a typo I spotted it should be `reinterpret_cast(opencv_mat.data)`, at least with my compiler. Other than this it worked fine, thanks! – dim_tz Feb 04 '16 at 16:19