ROS环境下无法从CompressedImage消息获取视频流问题求助
代码问题排查
错误点列表
- 订阅者未绑定回调函数:
rospy.Subscriber()调用时缺少回调函数参数,ROS接收到话题消息后不会触发任何处理逻辑,你的图像解析、窗口显示代码完全不会执行。 - 回调函数参数和实例调用错误:
camera_callback是全局函数,不需要self参数;同时你没有初始化CvBridge实例,直接调用self.CvBridge属于语法错误,程序运行时会直接抛出异常中断。 - 全局变量未声明:你在
camera_callback中修改全局变量global_frame时没有加global关键字,修改的只是函数内的局部变量,后续的读取操作也无法拿到正确的图像数据。 cv2.waitKey参数错误:主循环中使用cv2.waitKey(0)会无限等待用户按键输入才继续执行,程序会一直卡在此处,就算前面的逻辑正常也无法刷新显示窗口,该参数应改为1~10之间的数值,表示每帧等待对应毫秒数即可。
修正后可运行参考代码
#!/usr/bin/env python import cv2 import numpy as np from sensor_msgs.msg import CompressedImage from cv_bridge import CvBridge, CvBridgeError import rospy import sys print(sys.version) print(cv2.__version__) height = 480 width = 640 global_frame = np.zeros((height,width,3), np.uint8) # 初始化CvBridge实例 bridge = CvBridge() def calculate_lane_pose(frame): # Display the resulting frame cv2.imshow('Frame', frame) def camera_callback(data): global global_frame try: global_frame = bridge.compressed_imgmsg_to_cv2(data) except CvBridgeError as e: print(e) height, width, channels = global_frame.shape print(height) cv2.imshow("Original", global_frame) def lane_pose_publisher(): # Set the node name rospy.init_node('lane_pose_publisher', anonymous=True) # 订阅者绑定回调函数 rospy.Subscriber('/camera/image_raw/compressed', CompressedImage, camera_callback, queue_size = 1) # set rate rate = rospy.Rate(30) # 和摄像头帧率匹配即可,无需设置过高 while not rospy.is_shutdown(): rate.sleep() # 等待1ms刷新窗口 if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows() if __name__ == '__main__': try: lane_pose_publisher() except rospy.ROSInterruptException: pass
内容的提问来源于stack exchange,提问作者gup08
相关产品推荐
相关产品推荐

