newb1
newb1

Reputation: 3

copying elements from an opencv matrix to a eigen matrix

I have a std::vector filled with 3x3 opencv matrices. I want to unfold the matrices and write them in a 9xn eigen::matrix.

std::vector<cv::Mat1d> cvMatrix;

// some code that generates a std::vector with 3880 cv matrices, the cv matrices have the size 3x3

Eigen::Matrix<double, Eigen::Dynamic, 9> eigenMatrix;
for (int i = 0; i < curvatures.size(); i++) {
    eigenMatrix.resize(i + 1, 9);
    for (int j = 0; j < 9; j++) {
        eigenMatrix(i, j) = cvMatrix[i](j / 3, j % 3);
    }
}

If I check the elements right after they are written (e.g. printing the values of eigenMatrix if i==10) everything seems to be find, but after the for loop is finished that does not hold anymore. Most of the elements in eigenMatrix seem to contain zeros. Does anyone can explain what happens here?

Upvotes: 0

Views: 129

Answers (1)

chtz
chtz

Reputation: 18807

eigenMatrix.resize(i + 1, 9); destroys the content of eigenMatrix. Since you already know the final dimension at the beginning, just write

Eigen::Matrix<double, Eigen::Dynamic, 9> eigenMatrix;
eigenMatrix.resize(curvatures.size(), 9);

or even just

Eigen::Matrix<double, Eigen::Dynamic, 9> eigenMatrix(curvatures.size(), 9);

before starting the for-loop.

If you need to resize a matrix, but keep the content, you can use conservativeResize() -- but that should be avoided since it requires a full copy for each resizing.

Upvotes: 2

Related Questions