0

This post show us how to map the cv::Mat to Eigen matrix without copy the data, it works fine, but there are one thing I do not understand.

Mat A(20, 20, CV_32FC1);
cv::randn(A, 0.0f, 1.0f); // random data

// Map the OpenCV matrix with Eigen:
Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> A_Eigen(A.ptr<float>(), A.rows, A.cols);

The problem is, the Mat A do not tell the A_Eigen how many bytes per row it should take, as far as I know the cv::Mat of OpenCV may or may not do padding on each row, do I need to tell the Eigen how many bytes per row (how?)?, or I can safely omit it?

Ps: I am using Eigen 3

Community
  • 1
  • 1
StereoMatching
  • 4,971
  • 6
  • 38
  • 70
  • 1
    I probably would use the [conversion functions](https://github.com/Itseez/opencv/blob/master/modules/core/include/opencv2/core/eigen.hpp) given by OpenCV (second answer to the linked question). [OpenCV doc](http://docs.opencv.org/master/d0/daf/group__core__eigen.html#ga28d4c291bb74c3b915e2fd62f03906b1&gsc.tab=0) – Miki Aug 24 '15 at 16:13
  • @Miki Thanks, The opencv solution will allocated new buffer and copy the data(for dynamic matrix), but I want to reuse existing buffer, when training a lot of data, reduce the usage of memory is crucial, else it may throw bad_alloc exception – StereoMatching Aug 25 '15 at 05:25

1 Answers1

1

Instead of using A.cols, use A.step (or A.step[0] or A.step[1]?). If the OpenCV matrix is not continuous, then m.step != m.cols*m.elemSize(). You'll just have to ignore any additional columns, e.g. with A_Eigen.block<0,0>(A.rows, A.cols).

Avi Ginsburg
  • 10,323
  • 3
  • 29
  • 56