OpenCV CV::Mat and Eigen::Matrix

后端 未结 5 1473
孤街浪徒
孤街浪徒 2020-11-29 00:55

Is there a reversible way to convert an OpenCV cv::Mat object to an Eigen::Matrix?

e.g., Some way of doing:

cv::Mat cvMat;
         


        
5条回答
  •  萌比男神i
    2020-11-29 01:21

    You can map arbitrary matrices between Eigen and OpenCV (without copying data).

    You have to be aware of two things though:

    • Eigen defaults to column-major storage, OpenCV stores row-major. Therefore, use the Eigen::RowMajor flag when mapping OpenCV data.

    • The OpenCV matrix has to be continuous (i.e. ocvMatrix.isContinuous() needs to be true). This is the case if you allocate the storage for the matrix in one go at the creation of the matrix (e.g. as in my example below, or if the matrix is the result of a operation like Mat W = A.inv();)

    Example:

    Mat A(20, 20, CV_32FC1);
    cv::randn(A, 0.0f, 1.0f); // random data
    
    // Map the OpenCV matrix with Eigen:
    Eigen::Map> A_Eigen(A.ptr(), A.rows, A.cols);
    
    // Do something with it in Eigen, create e.g. a new Eigen matrix:
    Eigen::Matrix B = A_Eigen.inverse();
    
    // create an OpenCV Mat header for the Eigen data:
    Mat B_OpenCV(B.rows(), B.cols(), CV_32FC1, B.data());
    

    For multi-channel matrices (e.g. images), you can use 'Stride' exactly as Pierluigi suggested in his comment!

提交回复
热议问题