Skip to content

Instantly share code, notes, and snippets.

@lb5160482
Created January 15, 2018 21:54
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lb5160482/e812a671f778c0c7b14f80612c5389f7 to your computer and use it in GitHub Desktop.
Save lb5160482/e812a671f778c0c7b14f80612c5389f7 to your computer and use it in GitHub Desktop.
Rotation matrix to quaternion conversion c++
inline float SIGN(float x) {
return (x >= 0.0f) ? +1.0f : -1.0f;
}
inline float NORM(float a, float b, float c, float d) {
return sqrt(a * a + b * b + c * c + d * d);
}
// quaternion = [w, x, y, z]'
Mat mRot2Quat(const Mat& m) {
float r11 = m.at<float>(0, 0);
float r12 = m.at<float>(0, 1);
float r13 = m.at<float>(0, 2);
float r21 = m.at<float>(1, 0);
float r22 = m.at<float>(1, 1);
float r23 = m.at<float>(1, 2);
float r31 = m.at<float>(2, 0);
float r32 = m.at<float>(2, 1);
float r33 = m.at<float>(2, 2);
float q0 = (r11 + r22 + r33 + 1.0f) / 4.0f;
float q1 = (r11 - r22 - r33 + 1.0f) / 4.0f;
float q2 = (-r11 + r22 - r33 + 1.0f) / 4.0f;
float q3 = (-r11 - r22 + r33 + 1.0f) / 4.0f;
if (q0 < 0.0f) {
q0 = 0.0f;
}
if (q1 < 0.0f) {
q1 = 0.0f;
}
if (q2 < 0.0f) {
q2 = 0.0f;
}
if (q3 < 0.0f) {
q3 = 0.0f;
}
q0 = sqrt(q0);
q1 = sqrt(q1);
q2 = sqrt(q2);
q3 = sqrt(q3);
if (q0 >= q1 && q0 >= q2 && q0 >= q3) {
q0 *= +1.0f;
q1 *= SIGN(r32 - r23);
q2 *= SIGN(r13 - r31);
q3 *= SIGN(r21 - r12);
}
else if (q1 >= q0 && q1 >= q2 && q1 >= q3) {
q0 *= SIGN(r32 - r23);
q1 *= +1.0f;
q2 *= SIGN(r21 + r12);
q3 *= SIGN(r13 + r31);
}
else if (q2 >= q0 && q2 >= q1 && q2 >= q3) {
q0 *= SIGN(r13 - r31);
q1 *= SIGN(r21 + r12);
q2 *= +1.0f;
q3 *= SIGN(r32 + r23);
}
else if (q3 >= q0 && q3 >= q1 && q3 >= q2) {
q0 *= SIGN(r21 - r12);
q1 *= SIGN(r31 + r13);
q2 *= SIGN(r32 + r23);
q3 *= +1.0f;
}
else {
printf("coding error\n");
}
float r = NORM(q0, q1, q2, q3);
q0 /= r;
q1 /= r;
q2 /= r;
q3 /= r;
Mat res = (Mat_<float>(4, 1) << q0, q1, q2, q3);
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment