@@ -252,32 +252,38 @@ def __init__(self, simulator: GalbotEduSim, camera_config: RgbCameraConfig):
252252 }
253253
254254 def rotation_matrix_to_quaternion (self , R ):
255- """Convert a 3x3 rotation matrix to a quaternion.
255+ """Convert a 3x3 rotation matrix to a quaternion using scipy .
256256
257257 Args:
258- R: 3x3 rotation matrix
258+ R: 3x3 rotation matrix (numpy.ndarray)
259259
260260 Returns:
261261 np.ndarray: Quaternion in [w, x, y, z] format
262262 """
263- w = np .sqrt (1 + R [0 , 0 ] + R [1 , 1 ] + R [2 , 2 ]) / 2
264- x = (R [2 , 1 ] - R [1 , 2 ]) / (4 * w )
265- y = (R [0 , 2 ] - R [2 , 0 ]) / (4 * w )
266- z = (R [1 , 0 ] - R [0 , 1 ]) / (4 * w )
267- return np .array ([w , x , y , z ])
263+ from scipy .spatial .transform import Rotation as SciRot
264+ rot = SciRot .from_matrix (R )
265+ # scipy返回的四元数格式为[x, y, z, w],需转换为[w, x, y, z]
266+ quat_xyzw = rot .as_quat ()
267+ quat_wxyz = np .array ([quat_xyzw [3 ], quat_xyzw [0 ], quat_xyzw [1 ], quat_xyzw [2 ]])
268+ return quat_wxyz
269+
268270
269271 def _quaternion_to_rotation_matrix (self , quaternion : np .ndarray ) -> np .ndarray :
270- """Convert quaternion [w, x, y, z] to 3x3 rotation matrix."""
271- w , x , y , z = quaternion
272- return np .array ([
273- [1 - 2 * (y ** 2 + z ** 2 ), 2 * (x * y - w * z ), 2 * (x * z + w * y )],
274- [2 * (x * y + w * z ), 1 - 2 * (x ** 2 + z ** 2 ), 2 * (y * z - w * x )],
275- [2 * (x * z - w * y ), 2 * (y * z + w * x ), 1 - 2 * (x ** 2 + y ** 2 )]
276- ])
272+ """Convert quaternion [w, x, y, z] to 3x3 rotation matrix using scipy."""
273+ from scipy .spatial .transform import Rotation as R
274+ # scipy的from_quat格式为[x, y, z, w]
275+ q = np .asarray (quaternion )
276+ if q .shape [0 ] != 4 :
277+ raise ValueError ("Quaternion must be of shape (4,), format [w, x, y, z]" )
278+ # 转换为[x, y, z, w]格式
279+ quat_xyzw = np .array ([q [1 ], q [2 ], q [3 ], q [0 ]])
280+ rot = R .from_quat (quat_xyzw )
281+ return rot .as_matrix ()
277282
278283 def _apply_coordinate_transform (self , rotation_matrix : np .ndarray , transform : np .ndarray ) -> np .ndarray :
279284 """Apply coordinate system transformation and return quaternion [w, x, y, z]."""
280- transformed = transform [:3 , :3 ] @ rotation_matrix @ transform [:3 , :3 ].T
285+ # transformed = transform[:3, :3] @ rotation_matrix @ transform[:3, :3].T
286+ transformed = np .matmul (rotation_matrix , transform [:3 , :3 ])
281287 return self .rotation_matrix_to_quaternion (transformed )
282288
283289 def get_parameters (self ) -> dict :
@@ -342,7 +348,7 @@ def get_rgb(self):
342348 return None
343349
344350 # Flip rgb img vertically
345- # Reason: the image returned by `read_pixels`` is upside-down compared to the usual image coordinates (origin at top-left).
351+ # Reason: the image returned by `read_pixels` is upside-down compared to the usual image coordinates (origin at top-left).
346352 reshaped_data = np .flipud (reshaped_data )
347353
348354 return reshaped_data
0 commit comments