Alex
Alex

Reputation: 1469

How to obtain quaternion from rotation matrix in Android?

I'm trying to obtain the orientation of an android device, and I need it to be in a quaternion structure (float[4] basically).

What I have now is this:

if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
    last_acc = (float[])event.values.clone();
}
else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
    last_mag = (float[])event.values.clone();
}
if (last_acc != null && last_mag != null){
    SensorManager.getRotationMatrix(rotation, inclination, last_acc, last_mag);
    SensorManager.getOrientation(rotation, orientation);

In "rotation", I have the 4x4 rotation matrix, and in orientation I have a float[3] vector where I have the azimuth, pitch and roll.

How can I get now the quaternion?

Upvotes: 3

Views: 11348

Answers (2)

BellyItcher
BellyItcher

Reputation: 51

If you don't mind only being available to API Level 9 and higher, you can use Sensor.TYPE_ROTATION_VECTOR, which returns a unit quaternion anyway and saves you the work. If fed an array of length 3, the values will be the vector portion of the quaternion satisfying sin(theta / 2) * u, where u is a 3D unit vector. If the array is of length 4, the fourth value will be the scalar value of the unit quaternion, cos(theta / 2).

http://developer.android.com/reference/android/hardware/SensorEvent.html#values

Upvotes: 4

Ali
Ali

Reputation: 58501

I wouldn't use Euler angles (roll, pitch, yaw), it pretty much screws up the stability of your app.

As for converting the rotation matrix to quaternion, Google says:

Upvotes: 6

Related Questions