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
msg.y = q
msg.z = q
msg.w = q
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, q, q, q)

more

1

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

Thanks, but I mean about the tf python api.

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

1

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