To convert from a rotation matrix to a quaternion one needs to compute the scalar a and the coefficients b, c and d for the basis quaternions i, j and k
(see right side of figure). Using quaternions facilitates the representation and application of a rotation.

Figure 2: Components of rotation matrix and quaternion
To be able to write the quaternion in the form (cos , sin v), the quaternion
q has to be normalized to a unit quaternion. The quaternion can be divided
by its norm for normalization so that kqk = 1.

Figure 3: Conversion from a quaternion to a 4 x 4 rotation matrix
The normalization of a rotation matrix using Euler angles is much more computationally expensive, since the matrix M has to be replaced by M(MTM)−1/2. Normalization of the matrix M is necessary to prevent the matrix to become non-orthogonal, which would result in rotation errors.
To obtain a rotation matrix from a quaternion, the Euler angles phi, theta and psi need to be computed (see figure above).
For specific information about the use of quaternions in nifti-1 see the mat44_to_quatern( <params> ) and quatern_to_mat44( <params> ) functions
in the nifti1_io.h and nifti1_io.c code from Robert Cox. Some general information is available in [1] and [2].
[1] R. Mukundan. Quaternions: From classical mechanics to computer graphics,
and beyond. In Proceedings of the 7th Asian Technology Conference in Mathematics 2002, 2002.
[2] E.W. Weisstein. Quaternion. From Mathworld – a Wolfram Web Resource. http://mathworld.wolfram.com/Quaternion.html.