You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:27:00