Search code examples
pythonros

How to get x,y from move_base/NavfnROS/plan in python


I want to save /move_base/NavfnROS/plan. But I can not get the x,y coordinates separately

my code is bellow:

#! /usr/bin/env python3
   
from mimetypes import init
import rospy
from geometry_msgs.msg import PoseStamped 
from nav_msgs.msg import Path

class Path1:
        
    def Callback(self,data):
        #print(data.poses)
        print(data.poses.pose.position.x)
        print(data.poses.pose.position.y)


    def path_sub(self):
        rospy.init_node('path', anonymous=True)
        self.ps_sub = rospy.Subscriber('/move_base/NavfnROS/plan', Path, self.Callback,queue_size=1)
        rospy.spin()
 

 
if __name__ == '__main__':
    try:
        path = Path1()
        path.path_sub()
        rospy.spin()
 
    except rospy.ROSInterruptException: pass

I run it ,it will show the failed msg below:

AttributeError: 'list' object has no attribute 'pose'

The output of data.poses is shown below:

header: 
  seq: 0
  stamp: 
    secs: 1658754226
    nsecs: 420705206
  frame_id: "map"
pose: 
  position: 
    x: -2.8999995961785316
    y: 0.050000447779893875
    z: 0.0
  orientation: 
    x: 0.0
    y: 0.0
    z: 0.0
    w: 1.0 

It can run normally, But I Only want X and Y of these pose in the Path


Solution

  • This is because ros Path messages are a list of poses. With the given information it's not possible to say exactly what you want, however, to extract x/y coords you need to specify what point on the path you want. Alternatively, you can just print out all coords for every point on the path such as:

        def Callback(self,data):
            #print(data.poses)
            print([x.pose.position.x for x in data.poses])
            print([y.pose.position.y for y in data.poses])