Home > Back-end >  numpy array is converting a 2D array into 3D array which is giving me an error
numpy array is converting a 2D array into 3D array which is giving me an error

Time:05-30

I am trying to find the rotation matrix from quaternion. I am using predefined functions from numpy and scipy. I have tried it for a long time and even tried to change the dimensions of the array. At first I was getting a 4D array. Something like (3,4,17291,1). I reshaped and reduced the size. Even after that the finction is taking a 3D array (4, 17291, 1).

quat_w = dat[[" IMU2.quat_w"]]
quat_i = dat[[" IMU2.quat_i"]]
quat_j = dat[[" IMU2.quat_j"]]
quat_k = dat[[" IMU2.quat_k"]]
len_array = len(quat_w)
quat_temp = np.array([quat_w, quat_i, quat_j, quat_k])
quat = np.reshape(quat_temp, (4, len_array))
from scipy.spatial.transform import Rotation as R
rot = R.from_quat([quat_w, quat_i, quat_j, quat_k])

Error:

ValueError                                Traceback (most recent call last)
Input In [86], in <cell line: 2>()
      1 from scipy.spatial.transform import Rotation as R
----> 2 rot = R.from_quat([quat_w, quat_i, quat_j, quat_k])
    File rotation.pyx:626, in scipy.spatial.transform.rotation.Rotation.from_quat()
        File rotation.pyx:515, in scipy.spatial.transform.rotation.Rotation.__init__()
        ValueError: Expected `quat` to have shape (4,) or (N x 4), got (4, 17219, 1).

CodePudding user response:

Rotate.from_quat expects to get a list of quaternions. You're not passing that. You're passing a list of four lists of coordinates. It wants the first row to have [x,y,z,w], then the next row to have another [x,y,z,w]. That means you need to transpose what you have.

You'll have to do something like this, untested of course, since we have none of your data:

quat_w = dat[[" IMU2.quat_w"]]
quat_i = dat[[" IMU2.quat_i"]]
quat_j = dat[[" IMU2.quat_j"]]
quat_k = dat[[" IMU2.quat_k"]]
quat = np.array([quat_i, quat_j, quat_k, quat_w]).T
from scipy.spatial.transform import Rotation as R
rot = R.from_quat(quat)

I am assuming here that quat_w and friends are just vectors of components. That is, a 1-D list of numbers.

  • Related