Thomas Kosch
Thomas Kosch

Reputation: 53

OpenCV: Matrix multiplication with a matrix containing Vec3d and a matrix containing doubles

I am using OpenCV for some time and now I hit the point where I need a multiplication of this type:

Define a matrix T, which contains elements of the type Vec3d1 . Matrix T has the size: M X N. Matrix T has to be multiplied with a Vector Phi, which has the size: N X 1, containing doubles as values. Each element of the result has to be the result of a matrix multiplication of both matrices.

I don't want to do a component-wise multiplication, but a "real" matrix multiplication, e.g. multiplying the first element of T2 with the first element of matrix J, then multiplying the second element of matrix T3 with the second element of matrix J. Do this until you completed the first row of T and then sum up the results. The result is a M X 1.

For example, if T would be a 3 X 2 matrix and Phi a 2 X 1 matrix, then the calculation should be T_11 * phi_11 + T_12 * phi_21 for the first value of the result. Currently I'm using two for loops which are slow:

for (int i = 0; i<M; ++i){
    cv::Mat summedResult = cv::Mat(3, 1, CV_64F, double(0));
    for (uint32 j = 0; j<N; ++j){
        summedResult = summedResult + 
        (cv::Mat(mMatrixT.at<cv::Vec3d>(i, j)) * mMatrixPhi.at<double>(j));
    }
    // The result matrix contains values of type Vec3d again
    mResultMatrix.at<cv::Vec3d>(i) = cv::Vec3d(summedResult);
}

More generally: Is it possible to efficiently multiply matrices containing Vec3ds and doubles in OpenCV?


1. three dimensional vector containing doubles.

2. coordinate: 1,1

3. coordinate: 1,2

Upvotes: 2

Views: 1505

Answers (1)

Micka
Micka

Reputation: 20160

I still don't know what kind of result you expect, but maybe try this:

Assuming that you have a MxN matrix of Vec3d and a Nx1 Matrix of type double, your result will be a Mx1 matrix of type Vec3d:

for (int i = 0; i<M; ++i)
    {
        cv::Vec3d summedResult; // here this must be a Vec3d instead of a matrix, if I assume the right result expection
        for (uint32 j = 0; j<N; ++j)
        {
            summedResult = summedResult + (mMatrixT.at<cv::Vec3d>(i, j) * mMatrixPhi.at<double>(j));
        }
        // The result matrix contains values of type Vec3d again
        mResultMatrix.at<cv::Vec3d>(i) = summedResult;
    }

EDIT:

ah sorry, didnt read to the end that your provided code works but is too slow... well, I expect that there is no optimization for that because mathematically this isnt defined. What you can do is to convert your Vec3d mat to a Mx(3*N) matrix and convert your Nx1 mat to a (3*N)x1 mat (3 times the same value before the next value) and use the OpenCV matrix product directly. But probably that's not faster because of the 3* bigger size of both matrices ;)

EDIT: will be a different result, since each element will be the sum of the Vec3d elements...

Upvotes: 0

Related Questions