Efficient C++ quaternion multiplication using cv::Mat

Jav_Rock picture Jav_Rock · May 28, 2012 · Viewed 7.3k times · Source

I want to multiply 2 quaternions, which are stored in a cv::Mat structure. I want the function to be as efficient as possible. I have the following code so far:

/** Quaternion multiplication
 *
 */
void multiplyQuaternion(const Mat& q1,const Mat& q2, Mat& q)
{
    // First quaternion q1 (x1 y1 z1 r1)
    const float x1=q1.at<float>(0);
    const float y1=q1.at<float>(1);
    const float z1=q1.at<float>(2);
    const float r1=q1.at<float>(3);

    // Second quaternion q2 (x2 y2 z2 r2)
    const float x2=q2.at<float>(0);
    const float y2=q2.at<float>(1);
    const float z2=q2.at<float>(2);
    const float r2=q2.at<float>(3);


    q.at<float>(0)=x1*r2 + r1*x2 + y1*z2 - z1*y2;   // x component
    q.at<float>(1)=r1*y2 - x1*z2 + y1*r2 + z1*x2;   // y component
    q.at<float>(2)=r1*z2 + x1*y2 - y1*x2 + z1*r2;   // z component
    q.at<float>(3)=r1*r2 - x1*x2 - y1*y2 - z1*z2;   // r component
}

Is this the fastest way with OpenCV? Would it be fastest using fixed-point arithmetic?

Answer

Stephan Dollberg picture Stephan Dollberg · May 28, 2012

In this tutorial different ways to access different pixels are covered. The Mat::at function was found to be about 10% slower in comparison to direct pixel access, probably due to the extra check in debug mode.

If you are really off for performance, you should rewrite your method with the 3 different methods mentioned in the text and then profile to find the one which is best in your situation.