Python tf.TransformListener() Examples

The following are 30 code examples of tf.TransformListener(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tf , or try the search function .
Example #1
Source File: carla_spectator_camera.py    From ros-bridge with MIT License 6 votes vote down vote up
def __init__(self):
        """
        Constructor
        """
        rospy.init_node('spectator_camera', anonymous=True)
        self.listener = tf.TransformListener()
        self.role_name = rospy.get_param("/role_name", "ego_vehicle")
        self.camera_resolution_x = rospy.get_param("~resolution_x", 800)
        self.camera_resolution_y = rospy.get_param("~resolution_y", 600)
        self.camera_fov = rospy.get_param("~fov", 50)
        self.host = rospy.get_param('/carla/host', '127.0.0.1')
        self.port = rospy.get_param('/carla/port', '2000')
        self.timeout = rospy.get_param("/carla/timeout", 2)
        self.world = None
        self.pose = None
        self.camera_actor = None
        self.ego_vehicle = None
        rospy.Subscriber("/carla/{}/spectator_pose".format(self.role_name),
                         PoseStamped, self.pose_received) 
Example #2
Source File: cv_detection_camera_helper.py    From AI-Robot-Challenge-Lab with MIT License 6 votes vote down vote up
def __init__(self, camera_name, base_frame, table_height):
        """
        Initialize the instance

        :param camera_name: The camera name. One of (head_camera, right_hand_camera)
        :param base_frame: The frame for the robot base
        :param table_height: The table height with respect to base_frame
        """
        self.camera_name = camera_name
        self.base_frame = base_frame
        self.table_height = table_height

        self.image_queue = Queue.Queue()
        self.pinhole_camera_model = PinholeCameraModel()
        self.tf_listener = tf.TransformListener()

        camera_info_topic = "/io/internal_camera/{}/camera_info".format(camera_name)
        camera_info = rospy.wait_for_message(camera_info_topic, CameraInfo)

        self.pinhole_camera_model.fromCameraInfo(camera_info)

        cameras = intera_interface.Cameras()
        cameras.set_callback(camera_name, self.__show_image_callback, rectify_image=True) 
Example #3
Source File: niryo_one_robot_state_publisher.py    From niryo_one_ros with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):

        # Tf listener (position + rpy) of end effector tool
        self.position = [0, 0, 0]
        self.rpy = [0, 0, 0]
        self.tf_listener = tf.TransformListener()

        # State publisher
        self.niryo_one_robot_state_publisher = rospy.Publisher(
            '/niryo_one/robot_state', RobotState, queue_size=5)

        # Get params from rosparams
        rate_tf_listener = rospy.get_param("/niryo_one/robot_state/rate_tf_listener")
        rate_publish_state = rospy.get_param("/niryo_one/robot_state/rate_publish_state")

        rospy.Timer(rospy.Duration(1.0 / rate_tf_listener), self.get_robot_pose)
        rospy.Timer(rospy.Duration(1.0 / rate_publish_state), self.publish_state)

        rospy.loginfo("Started Niryo One robot state publisher") 
Example #4
Source File: base_control_utils.py    From pyrobot with MIT License 6 votes vote down vote up
def __init__(self, configs):
        self.configs = configs
        self.ROT_VEL = self.configs.BASE.MAX_ABS_TURN_SPEED
        self.LIN_VEL = self.configs.BASE.MAX_ABS_FWD_SPEED
        self.MAP_FRAME = self.configs.BASE.MAP_FRAME
        self.BASE_FRAME = self.configs.BASE.VSLAM.VSLAM_BASE_FRAME
        self.point_idx = self.configs.BASE.TRACKED_POINT

        rospy.wait_for_service(self.configs.BASE.PLAN_TOPIC, timeout=3)
        try:
            self.plan_srv = rospy.ServiceProxy(self.configs.BASE.PLAN_TOPIC, GetPlan)
        except rospy.ServiceException:
            rospy.logerr(
                "Timed out waiting for the planning service. \
                    Make sure build_map in script and \
                           use_map in roslauch are set to the same value"
            )
        self.start_state = build_pose_msg(0, 0, 0, self.BASE_FRAME)
        self.tolerance = self.configs.BASE.PLAN_TOL
        self._transform_listener = tf.TransformListener() 
Example #5
Source File: transform_integrator.py    From costar_plan with Apache License 2.0 6 votes vote down vote up
def __init__(self, name, root,
            listener=None,
            broadcaster=None,
            history_length=0,
            offset=None):
        self.name = name
        self.transforms = {}
        self.root = root
        self.history = deque()
        self.history_length = history_length
        self.offset = offset


        if listener is not None:
            self.listener = listener
        else:
            self.listener = tf.TransformListener()
        if broadcaster is not None:
            self.broadcaster = broadcaster
        else:
            self.broadcaster = tf.TransformBroadcaster() 
Example #6
Source File: urdf_to_collision_object.py    From costar_plan with Apache License 2.0 6 votes vote down vote up
def __init__(self, root="/world", listener=None, max_dt=1.):
        self.objs = {}
        self.urdfs = {}
        self.frames = {}
        if listener is None:
            self.listener = tf.TransformListener()
        else:
            self.listener = listener
        self.root = root
        self.max_dt = max_dt

        rospy.wait_for_service('/get_planning_scene')

        self.co_pub = rospy.Publisher('collision_object',
                CollisionObject,
                queue_size=1000) 
Example #7
Source File: rosTools.py    From crazyflieROS with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, options, parent=None):
        super(ROSNode, self).__init__(parent)

        self.compiledMsgs = [m for m in dir(msgCF) if m[0]!="_" and m[-2:]=="CF"] # Messages that are previously auto-compiled and we can send
        if len(self.compiledMsgs)==0:
            rospy.logerror('Not Messages could be loaded. Please connect to the flie and press Compile Messages, then run rosmake')
        self.options = options
        # Publishers
        self.publishers   = {} #Generated publishers will go here
        self.pub_tf       = tf.TransformBroadcaster()

        # Subscribers
        self.sub_tf    = tf.TransformListener()
        self.sub_joy   = rospy.Subscriber("/cfjoy", cmdMSG, self.receiveJoystick)
        self.sub_baro = None # Defined later

        self.master = rosgraph.Master('/rostopic') 
Example #8
Source File: head.py    From intera_sdk with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        """
        Constructor.
        """
        self._state = dict()

        self._pub_pan = rospy.Publisher(
            '/robot/head/command_head_pan',
            HeadPanCommand,
            queue_size=10)

        state_topic = '/robot/head/head_state'
        self._sub_state = rospy.Subscriber(
            state_topic,
            HeadState,
            self._on_head_state)

        self._tf_listener = tf.TransformListener()

        intera_dataflow.wait_for(
            lambda: len(self._state) != 0,
            timeout=5.0,
            timeout_msg=("Failed to get current head state from %s" %
                         (state_topic,)),
        ) 
Example #9
Source File: vehicle_position_validate.py    From fssim with MIT License 6 votes vote down vote up
def __init__(self, mission, ignore_track_check, track_details = None):

        # ROS Subscribers
        self.sub_track = rospy.Subscriber('/fssim/track', Track, self.callback_track)

        self.received_track = False
        self.ignore_track_check = ignore_track_check
        self.mission = mission

        # If we find detailed track description we can set also initial position
        self.track_details = track_details

        # TF Initializations
        self.listener = tf.TransformListener()
        self.br = tf2_ros.StaticTransformBroadcaster()

        # Track Cones
        self.cones_left = []
        self.cones_right = [] 
Example #10
Source File: detect_aruco.py    From flock with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        # ArUco data -- we're using 6x6 ArUco images
        self._aruco_dict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_6X6_250)
        self._aruco_parameters = cv2.aruco.DetectorParameters_create()

        # Initialize ROS
        rospy.init_node('detect_aruco_node', anonymous=False)

        # ROS publishers
        self._image_pub = rospy.Publisher('image_marked', Image, queue_size=10)
        self._rviz_markers_pub = rospy.Publisher('rviz_markers', MarkerArray, queue_size=10)

        # ROS OpenCV bridge
        self._cv_bridge = CvBridge()

        # ROS transform managers
        self._tf_listener = tf.TransformListener()
        self._tf_broadcaster = tf.TransformBroadcaster()

        # Get base_link => camera_frame transform
        self._tf_listener.waitForTransform("base_link", "camera_frame", rospy.Time(), rospy.Duration(4))
        self._Tcb = tf_to_matrix(self._tf_listener.lookupTransform("base_link", "camera_frame", rospy.Time()))

        # Now that we're initialized, set up subscriptions and spin
        rospy.Subscriber("image_raw", Image, self.image_callback)
        rospy.spin() 
Example #11
Source File: naoqi_moveto.py    From naoqi_bridge with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        NaoqiNode.__init__(self, 'naoqi_moveto_listener')
        self.connectNaoQi()
        self.listener = tf.TransformListener()

        self.goal_sub = rospy.Subscriber('move_base_simple/goal', PoseStamped, self.goalCB)
        self.cvel_sub = rospy.Subscriber('cmd_vel', Twist, self.cvelCB)


    # (re-) connect to NaoQI: 
Example #12
Source File: run_husky.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.index = 0
        self.gazeboModels = None
        self.img_np = None
        self.pose = Odometry()
        self.action = Twist()

        rospy.Subscriber(overheadImageTopic, Image, self.imageCallback)
        rospy.Subscriber(huskyCmdVelTopic, Twist, self.cmdVelCallback)

        self.listener = tf.TransformListener()
        self.writer = NpzDataset('husky_data')

        self.trans = None
        self.rot = None
        self.roll, self.pitch, self.yaw = 0., 0., 0.

        self.trans_threshold = 0.25

        rospy.wait_for_service("/gazebo/pause_physics")
        self.pause = rospy.ServiceProxy("/gazebo/pause_physics", EmptySrv)
        self.unpause = rospy.ServiceProxy("/gazebo/unpause_physics", EmptySrv)
        self.set_model_state = rospy.ServiceProxy("/gazebo/set_model_state",
                SetModelState)
        self.set_link_state = rospy.ServiceProxy("/gazebo/set_link_state",
                SetLinkState)
        self.get_link_state = rospy.ServiceProxy("/gazebo/get_link_state",
                GetLinkState)
        self.pose = None 
Example #13
Source File: husky_test_data_write.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.index = 0
        self.gazeboModels = None
        self.img_np = None
        self.pose = Odometry()
        self.action = Twist()

        rospy.Subscriber(overheadImageTopic, Image, self.imageCallback)
        rospy.Subscriber(huskyCmdVelTopic, Twist, self.cmdVelCallback)

        self.listener = tf.TransformListener()
        self.writer = NpzDataset('husky_data')

        self.trans = None
        self.rot = None
        self.roll, self.pitch, self.yaw = 0., 0., 0.

        self.trans_threshold = 0.25

        rospy.wait_for_service("/gazebo/pause_physics")
        self.pause = rospy.ServiceProxy("/gazebo/pause_physics", EmptySrv)
        self.unpause = rospy.ServiceProxy("/gazebo/unpause_physics", EmptySrv)
        self.set_model_state = rospy.ServiceProxy("/gazebo/set_model_state",
                SetModelState)
        self.set_link_state = rospy.ServiceProxy("/gazebo/set_link_state",
                SetLinkState)
        self.get_link_state = rospy.ServiceProxy("/gazebo/get_link_state",
                GetLinkState)
        self.pose = None 
Example #14
Source File: proxy_transform_listener.py    From flexbe_behavior_engine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        if ProxyTransformListener._listener is None:
            ProxyTransformListener._listener = tf.TransformListener() 
Example #15
Source File: dock_with_bin.py    From rosbook with Apache License 2.0 5 votes vote down vote up
def __init__(self):
    self.move_base = actionlib.SimpleActionClient('move_base', MoveBaseAction)
    self.move_base.wait_for_server()
    self.tf_listener = tf.TransformListener()
    self.head_client = actionlib.SimpleActionClient("head_controller/point_head", PointHeadAction)
    self.head_client.wait_for_server() 
Example #16
Source File: transform_listener.py    From scikit-robot with MIT License 5 votes vote down vote up
def __init__(self, use_tf2=True):
        if use_tf2:
            try:
                self.tf_listener = tf2_ros.BufferClient("/tf2_buffer_server")
                ok = self.tf_listener.wait_for_server(rospy.Duration(10))
                if not ok:
                    raise Exception(
                        "timed out: wait_for_server for 10.0 seconds")
            except Exception as e:
                rospy.logerr("Failed to initialize tf2 client: %s" % str(e))
                rospy.logwarn("Fallback to tf client")
                use_tf2 = False
        if not use_tf2:
            self.tf_listener = tf.TransformListener()
        self.use_tf2 = use_tf2 
Example #17
Source File: base_controllers.py    From pyrobot with MIT License 5 votes vote down vote up
def __init__(self, bot_base, ctrl_pub, configs):
        """
        The constructor for ProportionalControl class.

        :param configs: configurations read from config file
        :param base_state: an object consisting of an
                           instance of BaseState.
        :param ctrl_pub: a ros publisher used to publish velocity
                         commands to base of the robot.

        :type configs: dict
        :type base_state: BaseState
        :type ctrl_pub: rospy.Publisher
        """

        self.configs = configs
        self.bot_base = bot_base

        self.MAP_FRAME = self.configs.BASE.MAP_FRAME
        self.BASE_FRAME = self.configs.BASE.VSLAM.VSLAM_BASE_FRAME

        self.ctrl_pub = ctrl_pub

        self.rot_move_thr = ROT_MOVE_THR
        # threshold for linear.. if its more than this then we consider its
        # moving
        self.lin_move_thr = LIN_MOVE_THR

        self.rot_max_vel = self.configs.BASE.MAX_ABS_TURN_SPEED_P_CONTROLLER
        self.lin_max_vel = self.configs.BASE.MAX_ABS_FWD_SPEED_P_CONTROLLER
        self.translation_treshold = self.configs.BASE.TRANSLATION_TRESHOLD

        # threshold between which if error lies, we think of task being don
        self.rot_error_thr = ROT_ERR_THR
        self.dist_error_thr = LIN_ERR_THR

        self.vel_delta = VEL_DELTA
        self.hz = HZ
        self._transform_listener = TransformListener()
        self.ignore_collisions = False 
Example #18
Source File: collect_calibration_data.py    From pyrobot with MIT License 5 votes vote down vote up
def __init__(self, botname):
        """
        Constructor, sets up arm and active camera.
        """
        self.bot = Robot(botname)
        self.bot.camera = CalibrationCamera(self.bot.configs)
        self.bot.camera.reset()
        # self.bot.arm.go_home()

        # Initialize listening for transforms
        self.listener = tf.TransformListener()
        rospy.sleep(1) 
Example #19
Source File: move_base.py    From kinova-movo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_current_pose(self):

        """
        Gets the current pose of the base frame in the global frame
        """
        current_pose = None
        listener = tf.TransformListener()
        rospy.sleep(1.0)
        try:
            listener.waitForTransform(self.global_frame, self.base_frame, rospy.Time(), rospy.Duration(1.0))
        except:
            pass
        try:
            (trans,rot) = listener.lookupTransform(self.global_frame, self.base_frame, rospy.Time(0))

            pose_parts = [0.0] * 7
            pose_parts[0]  = trans[0]
            pose_parts[1]  = trans[1]
            pose_parts[2]  = 0.0
            euler = tf.transformations.euler_from_quaternion(rot)
            rot = tf.transformations.quaternion_from_euler(0,0,euler[2])
            pose_parts[3] = rot[0]
            pose_parts[4] = rot[1]
            pose_parts[5] = rot[2]
            pose_parts[6] = rot[3]

            current_pose = PoseWithCovarianceStamped()
            current_pose.header.stamp = rospy.get_rostime()
            current_pose.header.frame_id = self.global_frame
            current_pose.pose.pose = Pose(Point(pose_parts[0], pose_parts[1], pose_parts[2]), Quaternion(pose_parts[3],pose_parts[4],pose_parts[5],pose_parts[6]))
        except:
            rospy.loginfo("Could not get transform from %(1)s->%(2)s"%{"1":self.global_frame,"2":self.base_frame})

        return current_pose 
Example #20
Source File: active_camera.py    From pyrobot with MIT License 5 votes vote down vote up
def __init__(self):
        self.cv_bridge = CvBridge()
        self.camera_info_lock = threading.RLock()
        self.ar_tag_lock = threading.RLock()

        # Setup to control camera.
        self.joint_cmd_srv = rospy.ServiceProxy(JOINT_COMMAND_TOPIC, JointCommand)

        # Subscribe to camera pose and instrinsic streams.
        rospy.Subscriber(JOINT_STATE_TOPIC, JointState, self._camera_pose_callback)
        rospy.Subscriber(
            ROSTOPIC_CAMERA_INFO_STREAM, CameraInfo, self.camera_info_callback
        )
        self.img = None
        rospy.Subscriber(
            ROSTOPIC_CAMERA_IMAGE_STREAM,
            Image,
            lambda x: self.img_callback(x, "img", "bgr8"),
        )
        self.depth = None
        rospy.Subscriber(
            ROSTOPIC_CAMERA_DEPTH_STREAM,
            Image,
            lambda x: self.img_callback(x, "depth", None),
        )
        self.depth_registered = None
        rospy.Subscriber(
            ROSTOPIC_ALIGNED_CAMERA_DEPTH_STREAM,
            Image,
            lambda x: self.img_callback(x, "depth_registered", None),
        )
        rospy.Subscriber(ROSTOPIC_AR_POSE_MARKER, AlvarMarkers, self.alvar_callback)
        self.img = None
        self.ar_tag_pose = None

        self._transform_listener = TransformListener()
        self._update_camera_extrinsic = True
        self.camera_extrinsic_mat = None
        self.set_pan_pub = rospy.Publisher(ROSTOPIC_SET_PAN, Float64, queue_size=1)
        self.set_tilt_pub = rospy.Publisher(ROSTOPIC_SET_TILT, Float64, queue_size=1) 
Example #21
Source File: estimate_depth.py    From baxter_demos with Apache License 2.0 5 votes vote down vote up
def __init__(self, limb):
        self.tf_listener = tf.TransformListener()
        self.limb = limb
        self.limb_iface = baxter_interface.Limb(limb)

        self.ir_reading = 0.4
        self.camera_model = None
        self.goal_poses = []
        self.done = False

        self.inc = params['servo_speed']
        self.min_ir_depth = params['min_ir_depth']
        self.camera_x = params['camera_x'] 
        self.camera_y = params['camera_y'] 
        self.object_height = params['object_height'] 
Example #22
Source File: helpers.py    From kinova-movo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        self._battery_low = False
        self._dyn_rsp_active = False
        self._operational_state = 0
        self.tfl = tf.TransformListener()
        rospy.sleep(3.0)        
        
        self.cmd_config_cmd_pub = rospy.Publisher('/movo/gp_command', ConfigCmd, queue_size=10)
        self.cmd_vel_pub = rospy.Publisher('/movo/manual_override/cmd_vel', Twist, queue_size=10)
        rospy.Subscriber("/movo/feedback/battery", Battery, self._handle_low_battery)
        rospy.Subscriber("/movo/feedback/status", Status, self._handle_status) 
Example #23
Source File: crazyflie.py    From crazyswarm with MIT License 5 votes vote down vote up
def __init__(self, crazyflies_yaml="../launch/crazyflies.yaml"):
        """Initialize the server. Waits for all ROS services before returning.

        Args:
            timeHelper (TimeHelper): TimeHelper instance.
            crazyflies_yaml (str): If ends in ".yaml", interpret as a path and load
                from file. Otherwise, interpret as YAML string and parse
                directly from string.
        """
        rospy.init_node("CrazyflieAPI", anonymous=False)
        rospy.wait_for_service("/emergency")
        self.emergencyService = rospy.ServiceProxy("/emergency", Empty)
        rospy.wait_for_service("/takeoff")
        self.takeoffService = rospy.ServiceProxy("/takeoff", Takeoff)
        rospy.wait_for_service("/land")
        self.landService = rospy.ServiceProxy("/land", Land)
        # rospy.wait_for_service("/stop")
        # self.stopService = rospy.ServiceProxy("/stop", Stop)
        rospy.wait_for_service("/go_to")
        self.goToService = rospy.ServiceProxy("/go_to", GoTo)
        rospy.wait_for_service("/start_trajectory");
        self.startTrajectoryService = rospy.ServiceProxy("/start_trajectory", StartTrajectory)
        rospy.wait_for_service("/update_params")
        self.updateParamsService = rospy.ServiceProxy("/update_params", UpdateParams)

        if crazyflies_yaml.endswith(".yaml"):
            with open(crazyflies_yaml, 'r') as ymlfile:
                cfg = yaml.load(ymlfile)
        else:
            cfg = yaml.load(crazyflies_yaml)

        self.tf = TransformListener()

        self.crazyflies = []
        self.crazyfliesById = dict()
        for crazyflie in cfg["crazyflies"]:
            id = int(crazyflie["id"])
            initialPosition = crazyflie["initialPosition"]
            cf = Crazyflie(id, initialPosition, self.tf)
            self.crazyflies.append(cf)
            self.crazyfliesById[id] = cf 
Example #24
Source File: DeadReckoning.py    From ROS-Programming-Building-Powerful-Robots with MIT License 5 votes vote down vote up
def __init__(self):
		rospy.init_node('DeadReckoning')
		
		self._VelocityCommandPublisher = rospy.Publisher("cmd_vel", Twist)
		self._TransformListener = tf.TransformListener()

		# wait for the listener to get the first transform message
		self._TransformListener.waitForTransform("/odom", "/base_link", rospy.Time(), rospy.Duration(4.0)) 
Example #25
Source File: DeadReckoning.py    From ROS-Programming-Building-Powerful-Robots with MIT License 5 votes vote down vote up
def __init__(self):
		rospy.init_node('DeadReckoning')
		
		self._VelocityCommandPublisher = rospy.Publisher("cmd_vel", Twist)
		self._TransformListener = tf.TransformListener()

		# wait for the listener to get the first transform message
		self._TransformListener.waitForTransform("/odom", "/base_link", rospy.Time(), rospy.Duration(4.0)) 
Example #26
Source File: DeadReckoning.py    From ROS-Programming-Building-Powerful-Robots with MIT License 5 votes vote down vote up
def __init__(self):
		rospy.init_node('DeadReckoning')
		
		self._VelocityCommandPublisher = rospy.Publisher("cmd_vel", Twist)
		self._TransformListener = tf.TransformListener()

		# wait for the listener to get the first transform message
		self._TransformListener.waitForTransform("/odom", "/base_link", rospy.Time(), rospy.Duration(4.0)) 
Example #27
Source File: quad_ros_env.py    From visual_dynamics with MIT License 5 votes vote down vote up
def __init__(self, dt=None):
        self.dt = dt or 0.1
        self.sensor_names = ['quad_to_obj_pos', 'quad_to_obj_rot', 'image']

        # self.quad_to_obj_pos = np.zeros(3)
        # self.quad_to_obj_rot = np.array([0, 0, 0, 1])
        # self.image = np.zeros((32, 32), dtype=np.uint8)
        # self.quad_pos = np.zeros(3)
        # self.quad_rot = np.array([0, 0, 0, 1])
        self.quad_to_obj_pos = None
        self.quad_to_obj_rot = None
        self.image = None
        self.quad_pos = None
        self.quad_rot = None

        self.camera_control_pub = rospy.Publisher("/bebop/camera_control", geometry_msgs.Twist, queue_size=1, latch=True)
        self.cmd_vel_pub = rospy.Publisher("/vservo/cmd_vel", geometry_msgs.Twist, queue_size=1)

        # set camera's tilt angle to -35 degrees
        twist_msg = geometry_msgs.Twist(
            linear=geometry_msgs.Point(0., 0., 0.),
            angular=geometry_msgs.Point(0., -35., 0.)
        )
        self.camera_control_pub.publish(twist_msg)

        self.listener = tf.TransformListener()
        self.image_sub = rospy.Subscriber("/bebop/image_raw", sensor_msgs.Image, callback=self._image_callback)
        self.cv_bridge = cv_bridge.CvBridge()

        self._action_space = TranslationAxisAngleSpace(-np.ones(4), np.ones(4), axis=np.array([0, 0, 1]))

        self.rate = rospy.Rate(1.0 / self.dt)

        rospy.sleep(1) 
Example #28
Source File: flieTracker.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        
        rospy.init_node('flieLocaliser') 
        
        self.maxDepth = 4.5
        self.bg_thresh = 0.45
        self.kernel = np.ones((3, 3), np.uint8)
        self.centerX = 319.5
        self.centerY = 239.5
        self.depthFocalLength = 525

        # CV stuff
        self.bridge = CvBridge()

           
        # Subscribe
        #self.sub_rgb = rospy.Subscriber("/camera/rgb/image_raw", ImageMSG, self.new_rgb_data)
        self.sub_depth = rospy.Subscriber("/camera/depth_registered/image_raw", ImageMSG, self.new_depth_data)
        self.pub_depth = rospy.Publisher("/camera/detector", ImageMSG)
        self.sub_tf = tf.TransformListener()

        # Publish
        self.pub_tf = tf.TransformBroadcaster()

        # Members
        self.depth = None
        self.show = None
        self.counter = 30*4

        self.acc = np.zeros((480,640,self.counter), dtype=np.float32)


        
        # Run ROS node
        rospy.loginfo('Node Started')
        try:
            rospy.spin()
        except KeyboardInterrupt:
            print "Shutting down"
            cv2.destroyAllWindows() 
Example #29
Source File: joy_driver.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,options=None):     
        self.options = options
           
        self.joy_scale = [-1,1,-1,1,1] #RPYTY
        self.trim_roll = 0
        self.trim_pitch = 0
        self.max_angle = 30
        self.max_yawangle = 200
        
        
        self.max_thrust = 80.
        self.min_thrust = 25.
        self.max_thrust_raw = percentageToThrust(self.max_thrust)
        self.min_thrust_raw = percentageToThrust(self.min_thrust)       
        self.old_thurst_raw = 0
        
        self.slew_limit = 45
        self.slew_rate = 30
        self.slew_limit_raw = percentageToThrust(self.slew_limit)            
        self.slew_rate_raw = percentageToThrust(self.slew_rate)   
        
        self.dynserver = None
        self.prev_cmd = None
        self.curr_cmd = None
        self.yaw_joy = True
        
        self.sub_joy   = rospy.Subscriber("/joy", JoyMSG, self.new_joydata)
        self.sub_tf    = tf.TransformListener()         
        self.pub_tf    = tf.TransformBroadcaster()    
        self.pub_cfJoy = rospy.Publisher("/cfjoy", CFJoyMSG)
        
        # Dynserver               
        
        self.dynserver = DynamicReconfigureServer(CFJoyCFG, self.reconfigure) 
Example #30
Source File: locobot.py    From pyrobot with MIT License 5 votes vote down vote up
def __init__(
        self,
        url=MODEL_URL,
        model_name="model.pth",
        n_samples=N_SAMPLES,
        patch_size=PATCH_SIZE,
        *kargs,
        **kwargs
    ):
        """ 
        The constructor for :class:`Grasper` class. 

        :param url: Link to the grasp model file
        :param model_name: Name of the path where the grasp model will be saved
        :param n_samples: Number of samples for the grasp sampler
        :param patch_size: Size of the patch for the grasp sampler
        :type url: string
        :type model_name: string
        :type n_samples: int
        :type patch_size: int
        """

        # TODO - use planning_mode=no_plan, its better
        self.robot = Robot(
            "locobot_kobuki",
            arm_config={"use_moveit": True, "moveit_planner": "ESTkConfigDefault"},
        )
        self.grasp_model = GraspModel(
            model_name=model_name, url=url, nsamples=n_samples, patchsize=patch_size
        )
        self.pregrasp_height = 0.2
        self.grasp_height = 0.13
        self.default_Q = Quaternion(0.0, 0.0, 0.0, 1.0)
        self.grasp_Q = Quaternion(0.0, 0.707, 0.0, 0.707)
        self.retract_position = list([-1.5, 0.5, 0.3, -0.7, 0.0])
        self.reset_pan = 0.0
        self.reset_tilt = 0.8
        self.n_tries = 5
        self._sleep_time = 2
        self._transform_listener = TransformListener()