Using ROS 2? Check out the ROS 2 tf2 tutorials.

(!) Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.

Migrating a TransformListener from tf to tf2

Description: This is a guide for converting a tf TransformListener class to a tf2 Listener class

Tutorial Level: INTERMEDIATE

Primary difference

The TransformListener uses the public API only and populates an independently allocated tf2::Buffer.

C++

Old Style

Depend on tf package.

   1 #include "tf/transform_listener.h"
   2 #include "tf/tf.h"
   3 tf::TransformListener tfl;
   4 
   5 ros::Time time = ...;
   6 ros::Duration timeout(1.0);
   7 
   8 tf::StampedTransform tf;
   9 if (!tfl.waitForTransform("target", "source", time, timeout)){
  10     # handle lookup error
  11 } else {
  12     tfl.lookupTransform("target", "source", time, tf);
  13 }

Equivalent Replacement

Depend on tf2_ros package and possibly also tf2_geometry_msgs.

   1 #include "tf2_ros/buffer.h"
   2 #include "tf2_ros/transform_listener.h"
   3 #include "tf2_geometry_msgs/tf2_geometry_msgs.h"
   4 
   5 tf2_ros::Buffer buffer;
   6 tf2_ros::TransformListener tfl(buffer);
   7 
   8 ros::Time time = ...;
   9 ros::Duration timeout(1.0);
  10 
  11 geometry_msgs::TransformStamped tfGeom;
  12 try {
  13     tfGeom = buffer.lookupTransform("target", "source", time, timeout);
  14 } catch (tf2::TransformException &e) {
  15     # handle lookup error
  16 }
  17 
  18 tf2::Stamped<tf2::Transform> tf2;
  19 tf2::convert(tfGeom, tf2);  # note that tf2 is missing child_frame_id

Python

Old Style

Depend on tf package.

   1 import tf
   2 tfl = tf.TransformListener()

Equivalent Replacement

Depend on tf_ros package.

   1 import tf2_ros
   2 buffer = tf2_ros.Buffer()
   3 tfl = tf2_ros.TransformListener(buffer)

Wiki: tf2/Tutorials/Migration/TransformListener (last edited 2022-10-06 16:52:34 by ShaneLoretz)