opencvtype-conversionarmadillomlpack

Conversion between cv::Mat and arma::mat


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!


Solution

  • 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() )