ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A answers.ros.org

# quaternions with python

I have recently started using rospy after being working with roscpp. I wanted to reproduce this piece of C++ code:

geometry_msgs::Quaternion quat = tf::createQuaternionMsgFromYaw(th);
geometry_msgs::PoseStamped goal;
goal.pose.orientation = quat;


For what I have found, the closest form would be something like:

quat = quaternion_to_msg(tf.transformations.quaternion_from_euler(0, 0, th))
goal = PoseStamped()
goal.pose.orientation = quat


But this actually does not work because 'quaternion_from_euler' returns a four float array, instead of an object with {x, y, z, w} fields.

I have searched for some common function to do this easy transform, but I have not found it within the ros libraries. What I have seen is that many people make his own implementation:

def quaternion_to_msg(q):
msg = Quaternion()
msg.x = q[0]
msg.y = q[1]
msg.z = q[2]
msg.w = q[3]
return msg

goal.pose.orientation = quaternion_to_msg(quat)


Does ROS provide a common solution for this situation?

edit retag close merge delete

Sort by ยป oldest newest most voted

Python has a nifty feature which allows you to expand a tuple into an argument list. Rather than setting all of the quaternion's fields individually, you can use the constructor as follows

q = tf.transformations.quaternion_from_euler(0, 0, th)
msg = Quaternion(*q)


This is equivalent to doing

q = tf.transformations.quaternion_from_euler(0, 0, th)
msg = Quaternion(q[0], q[1], q[2], q[3])

more

1

Where can one find documentation on these mysterious functions ? http://ros.org/doc/groovy/api/tf/html/python/ is quite... primitive.

( 2013-03-18 22:52:47 -0500 )edit

This is a python feature, not ROS. As such, it is documented in the python docs: http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists

( 2013-03-19 04:50:46 -0500 )edit

Thanks, but I mean about the tf python api.

( 2013-03-19 05:26:10 -0500 )edit

What do you mean? The tf api docs look pretty complete to me.

( 2013-03-19 05:49:34 -0500 )edit
1

Is there documentation for the tf.transformation module?

( 2014-01-05 03:23:24 -0500 )edit

I'd highly recommend taking a look at PyKDL, which is part of the KDL library here or here. It has well tested support for working with quaternions, Euler angles, axis-angle, etc.

more