python程式釋出和訂閱ros話題
阿新 • • 發佈:2018-12-21
編寫talker.py:
這個檔案呼叫了opencv開啟攝像頭獲取影象併發布出去
#!/usr/bin/env python # license removed for brevity import rospy from sensor_msgs.msg import Image import cv2 from cv_bridge import CvBridge def talker(): pub = rospy.Publisher('/tutorial/image', Image, queue_size=1) rospy.init_node('talker', anonymous=True) rate = rospy.Rate(30) bridge = CvBridge() Video = cv2.VideoCapture(0) while not rospy.is_shutdown(): ret, img = Video.read() cv2.imshow("talker", img) cv2.waitKey(3) pub.publish(bridge.cv2_to_imgmsg(img, "bgr8")) rate.sleep() if __name__ == '__main__': try: talker() except rospy.ROSInterruptException: pass
編寫listener.py:
這個檔案訂閱talker的話題並獲取影象。
#!/usr/bin/env python import rospy from sensor_msgs.msg import Image import cv2 from cv_bridge import CvBridge def callback(imgmsg): bridge = CvBridge() img = bridge.imgmsg_to_cv2(imgmsg, "bgr8") cv2.imshow("listener", img) cv2.waitKey(3) def listener(): # In ROS, nodes are uniquely named. If two nodes with the same # node are launched, the previous one is kicked off. The # anonymous=True flag means that rospy will choose a unique # name for our 'listener' node so that multiple listeners can # run simultaneously. rospy.init_node('listener', anonymous=True) rospy.Subscriber("/tutorial/image", Image, callback) # spin() simply keeps python from exiting until this node is stopped rospy.spin() if __name__ == '__main__': listener()
開啟三個終端執行roscore,以上兩個py檔案就可以呼叫攝像頭髮布的image資訊