当前位置:   article > 正文

ROS回调函数的类方法实现,both in Python 和 C++_ros 回调函数 怎么写

ros 回调函数 怎么写

一、常用的回调函数的实现

C++版本

ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
  • 1

python版本

rospy.Subscriber(topic, Image, callback, queue_size=1)
  • 1

二、用类的方法实现回调函数

C++版本

class Listener
{
public:
  void callback(const std_msgs::String::ConstPtr& msg);
};

Listener listener;
ros::Subscriber sub = n.subscribe("chatter", 1000, &Listener::callback, &listener);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

python 版本

class RecordTopic:

    def __init__(self):
        rospy.Subscriber(topic, Image, self.callback, queue_size=1)

    def callback(self, imgmsg):
        #callback

if __name__=='__main__':
    rospy.init_node('node_name', anonymous=True)
    topic = sys.argv[1]
    record_topic = RecordTopic()
    rospy.spin()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

三、特殊情况记录

在使用回调函数时,我有自己的一种方式,不知道会存在什么问题。不过我发现了一种特殊的现象,于是记录在这里。

首先,我的使用方式如下:

import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import thread
import sys

im = cv2.imread('')
flag_im = False

def imSub(imgmsg): #回调函数, 仅用于更新图像信息
  global im, flag_im
  bridge = CvBridge()
  im = bridge.imgmsg_to_cv2(imgmsg, 'bgr8')
  flag_im = True

def call_rosspin():
  print 'call_rosspin: running rosspin'
  rospy.spin()

if __name__ == '__main__':
  argc = len(sys.argv)
  if argc < 2:
    print 'please input topicname'
    sys.exit()
  else:
    topicname = sys.argv[1]
    if argc == 2:
      filename = 'imsave.jpg'
    else:
      filename = argv[2]
  rospy.init_node('imsave')
  im_sub = rospy.Subscriber(topicname, Image, imSub)
  thread.start_new_thread(call_rosspin, ()) #使用多线程的方式调用回调函数,更新图像

  key = 100
  cv2.namedWindow('im')
  while key != ord('q'): #主循环,做需要进行的工作
    if flag_im:
      flag_im = False
      cv2.imshow('im', im)
    key = cv2.waitKey(1)
    key = key&0xFF
    if key == ord('s'):
      cv2.imwrite(filename, im)
      print 'pic is saved as', filename
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

发现的问题

以上面多线程的使用方式,图像显示更具有实时性;而以常规方式实现的回调函数,看到的画面会有一定时间的延迟。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/49912
推荐阅读
相关标签
  

闽ICP备14008679号