Skip to content

Convert from rvec to quaternion using nalgebra? #668

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
lucasw opened this issue Apr 25, 2025 · 2 comments
Open

Convert from rvec to quaternion using nalgebra? #668

lucasw opened this issue Apr 25, 2025 · 2 comments

Comments

@lucasw
Copy link

lucasw commented Apr 25, 2025

If I get an rvec back from for example opencv::aruco::estimate_pose_charuco_board_def(), how can I convert it to a quaternion (ideally using nalgebra or similar, not the error prone cutting and pasting of a big block of quaternion math code)?

This isn't really an issue with opencv-rust, it may go better in a discussion section if that were enabled here.

I'll probably have it figured out in a little while, and I'll post the answer and maybe it'll save someone else some time.

@lucasw
Copy link
Author

lucasw commented Apr 25, 2025

I think this is it, but I'll need to test it:

let rslice = rvec.as_slice();
let axisangle = nalgebra::Vector3::new(rslice[0], rslice[1], rslice[2]);
let rot = nalgebra::Rotation3::new(axisangle);
let q = nalgebra::UnitQuaternion::from_rotation_matrix(&rot);
...
pose.orientation.w = q.coords.w;
pose.orientation.x = q.coords.x;
pose.orientation.y = q.coords.y;
pose.orientation.z = q.coords.z;

this appears to be the same as with this python, though multiplied by -1:

import cv2
import numpy as np
from scipy.spatial.transform import Rotation as R

rvec = np.array([0.0064893401728181345, -0.04393382349777288, -1.8669626173081237])
rvec_matrix = cv2.Rodrigues(rvec)[0]
rotation = R.from_matrix(rvec_matrix)
quaternion = rotation.as_quat()

@OlivierLDff
Copy link

OlivierLDff commented Apr 26, 2025

I find myself often using glam library for this purpose:

let r_vec = glam::Vec3::new(x, y, z);
let quat = glam::Quat::from_scaled_axis(r_vec);
let r_mat = glam::Mat3::from_quat(quat);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants