|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import rclpy |
| 3 | +from rclpy.node import Node |
| 4 | +from sensor_msgs.msg import Image, Imu |
| 5 | +import cv2 |
| 6 | +from cv_bridge import CvBridge |
| 7 | +import pyrealsense2 as rs |
| 8 | +import numpy as np |
| 9 | +from typing import List, Dict, Tuple, Optional |
| 10 | + |
| 11 | +class CameraPublisherFull(Node): |
| 12 | + def __init__(self): |
| 13 | + super().__init__('camera_publisher_full') |
| 14 | + self.bridge = CvBridge() |
| 15 | + |
| 16 | + # Initialize RealSense if present |
| 17 | + self.rs_pipeline = None |
| 18 | + self.rs_config = None |
| 19 | + self.rs_publishers = {} |
| 20 | + self.imu_publisher = self.create_publisher(Imu, '/camera/imu/data', 30) |
| 21 | + self.has_realsense = self.setup_realsense() |
| 22 | + |
| 23 | + # Initialize standard cameras (regardless of RealSense detection) |
| 24 | + self.std_publishers = [] |
| 25 | + self.std_caps = [] |
| 26 | + self.std_dev_paths = [] |
| 27 | + |
| 28 | + # Auto-detect available standard camera devices |
| 29 | + device_paths = self.detect_available_cameras() |
| 30 | + for i, dev_path in enumerate(device_paths): |
| 31 | + pub = self.create_publisher(Image, f'cam_{i}', 30) |
| 32 | + cap = cv2.VideoCapture(dev_path) |
| 33 | + if not cap.isOpened(): |
| 34 | + self.get_logger().error(f'Could not open video device at: {dev_path}') |
| 35 | + continue |
| 36 | + self.std_publishers.append(pub) |
| 37 | + self.std_caps.append(cap) |
| 38 | + self.std_dev_paths.append(dev_path) |
| 39 | + |
| 40 | + # Check if we have any camera at all |
| 41 | + if not self.has_realsense and len(self.std_caps) == 0: |
| 42 | + self.get_logger().error('No active video devices found.') |
| 43 | + exit(1) |
| 44 | + |
| 45 | + # Setup timer callback |
| 46 | + self.timer_period = 0.033 # ~30 FPS |
| 47 | + self.timer = self.create_timer(self.timer_period, self.timer_callback) |
| 48 | + |
| 49 | + def setup_realsense(self) -> bool: |
| 50 | + """Initialize RealSense camera if available and IMU stream""" |
| 51 | + try: |
| 52 | + # Create pipeline and config |
| 53 | + self.rs_pipeline = rs.pipeline() |
| 54 | + self.rs_config = rs.config() |
| 55 | + |
| 56 | + # Try to find RealSense devices |
| 57 | + ctx = rs.context() |
| 58 | + devices = ctx.query_devices() |
| 59 | + if len(devices) == 0: |
| 60 | + self.get_logger().info('No RealSense devices detected') |
| 61 | + return False |
| 62 | + |
| 63 | + # Setup streams for the first RealSense device |
| 64 | + self.get_logger().info(f'Found RealSense device: {devices[0].get_info(rs.camera_info.name)}') |
| 65 | + |
| 66 | + # Enable video streams |
| 67 | + self.rs_config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30) |
| 68 | + self.rs_config.enable_stream(rs.stream.infrared, 1, 640, 480, rs.format.y8, 30) |
| 69 | + self.rs_config.enable_stream(rs.stream.infrared, 2, 640, 480, rs.format.y8, 30) |
| 70 | + self.rs_config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) |
| 71 | + |
| 72 | + # Enable IMU stream |
| 73 | + self.rs_config.enable_stream(rs.stream.accel, rs.format.motion_xyz32f, 30) |
| 74 | + self.rs_config.enable_stream(rs.stream.gyro, rs.format.motion_xyz32f, 30) |
| 75 | + |
| 76 | + # Start streaming |
| 77 | + self.rs_pipeline.start(self.rs_config) |
| 78 | + |
| 79 | + # Create publishers for each stream |
| 80 | + self.rs_publishers['color'] = self.create_publisher(Image, '/camera/color/image_raw', 30) |
| 81 | + self.rs_publishers['infra1'] = self.create_publisher(Image, '/camera/infra1/image_rect_raw', 30) |
| 82 | + self.rs_publishers['infra2'] = self.create_publisher(Image, '/camera/infra2/image_rect_raw', 30) |
| 83 | + self.rs_publishers['depth'] = self.create_publisher(Image, '/camera/depth/image_rect_raw', 30) |
| 84 | + |
| 85 | + self.get_logger().info('RealSense camera initialized successfully') |
| 86 | + return True |
| 87 | + |
| 88 | + except Exception as e: |
| 89 | + self.get_logger().warn(f'Failed to initialize RealSense: {e}') |
| 90 | + return False |
| 91 | + |
| 92 | + def detect_available_cameras(self) -> List[str]: |
| 93 | + """Detect standard USB cameras, excluding RealSense devices""" |
| 94 | + available_cameras = [] |
| 95 | + max_tested = 10 |
| 96 | + |
| 97 | + for i in range(max_tested): |
| 98 | + cap = cv2.VideoCapture(f'/dev/video{i}') |
| 99 | + if cap.isOpened(): |
| 100 | + # Check if this is not a RealSense camera by looking at properties |
| 101 | + name = cap.getBackendName() |
| 102 | + if 'realsense' not in name.lower(): |
| 103 | + available_cameras.append(f'/dev/video{i}') |
| 104 | + else: |
| 105 | + self.get_logger().info(f'Skipping RealSense camera at /dev/video{i}') |
| 106 | + cap.release() |
| 107 | + |
| 108 | + self.get_logger().info(f'Detected standard camera devices: {available_cameras}') |
| 109 | + return available_cameras |
| 110 | + |
| 111 | + def publish_realsense_frame(self, frame, frame_type): |
| 112 | + if frame_type in self.rs_publishers: |
| 113 | + if frame_type in ['color', 'infra1', 'infra2', 'depth']: |
| 114 | + # Process image based on type |
| 115 | + if frame_type == 'color': |
| 116 | + # Convert BGR to RGB |
| 117 | + img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| 118 | + msg = self.bridge.cv2_to_imgmsg(img, encoding="rgb8") |
| 119 | + elif frame_type in ['infra1', 'infra2']: |
| 120 | + # Infrared is already grayscale (y8) |
| 121 | + msg = self.bridge.cv2_to_imgmsg(frame, encoding="mono8") |
| 122 | + else: # depth |
| 123 | + # Depth is 16-bit |
| 124 | + msg = self.bridge.cv2_to_imgmsg(frame, encoding="16UC1") |
| 125 | + |
| 126 | + self.rs_publishers[frame_type].publish(msg) |
| 127 | + |
| 128 | + def publish_imu_data(self, accel_data, gyro_data): |
| 129 | + imu_msg = Imu() |
| 130 | + imu_msg.header.stamp = self.get_clock().now().to_msg() |
| 131 | + |
| 132 | + # Fill in IMU data for linear acceleration |
| 133 | + imu_msg.linear_acceleration.x = accel_data[0] |
| 134 | + imu_msg.linear_acceleration.y = accel_data[1] |
| 135 | + imu_msg.linear_acceleration.z = accel_data[2] |
| 136 | + |
| 137 | + # Fill in IMU data for angular velocity |
| 138 | + imu_msg.angular_velocity.x = gyro_data[0] |
| 139 | + imu_msg.angular_velocity.y = gyro_data[1] |
| 140 | + imu_msg.angular_velocity.z = gyro_data[2] |
| 141 | + |
| 142 | + self.imu_publisher.publish(imu_msg) |
| 143 | + |
| 144 | + def timer_callback(self): |
| 145 | + # Process RealSense frames if available |
| 146 | + if self.has_realsense: |
| 147 | + try: |
| 148 | + frames = self.rs_pipeline.wait_for_frames() |
| 149 | + |
| 150 | + # Process camera frames |
| 151 | + color_frame = frames.get_color_frame() |
| 152 | + if color_frame: |
| 153 | + color_image = np.asanyarray(color_frame.get_data()) |
| 154 | + self.publish_realsense_frame(color_image, 'color') |
| 155 | + |
| 156 | + depth_frame = frames.get_depth_frame() |
| 157 | + if depth_frame: |
| 158 | + depth_image = np.asanyarray(depth_frame.get_data()) |
| 159 | + self.publish_realsense_frame(depth_image, 'depth') |
| 160 | + |
| 161 | + # Process infrared frames |
| 162 | + for i in [1, 2]: |
| 163 | + ir_frame = frames.get_infrared_frame(i) |
| 164 | + if ir_frame: |
| 165 | + ir_image = np.asanyarray(ir_frame.get_data()) |
| 166 | + self.publish_realsense_frame(ir_image, f'infra{i}') |
| 167 | + |
| 168 | + # Process IMU frames |
| 169 | + accel_frame = frames.first(rs.stream.accel) |
| 170 | + gyro_frame = frames.first(rs.stream.gyro) |
| 171 | + if accel_frame and gyro_frame: |
| 172 | + accel_data = accel_frame.as_motion_frame().get_motion_data() |
| 173 | + gyro_data = gyro_frame.as_motion_frame().get_motion_data() |
| 174 | + self.publish_imu_data(accel_data, gyro_data) |
| 175 | + |
| 176 | + except Exception as e: |
| 177 | + self.get_logger().error(f'Error processing RealSense frames: {e}') |
| 178 | + |
| 179 | + # Process standard camera frames |
| 180 | + for i in range(len(self.std_caps)): |
| 181 | + cap = self.std_caps[i] |
| 182 | + dev_path = self.std_dev_paths[i] |
| 183 | + ret, frame = cap.read() |
| 184 | + if ret: |
| 185 | + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| 186 | + msg = self.bridge.cv2_to_imgmsg(frame, encoding="rgb8") |
| 187 | + self.std_publishers[i].publish(msg) |
| 188 | + else: |
| 189 | + pass |
| 190 | + |
| 191 | +def main(args=None): |
| 192 | + # Initialize node |
| 193 | + rclpy.init(args=args) |
| 194 | + node = CameraPublisherFull() |
| 195 | + try: |
| 196 | + # Spin |
| 197 | + rclpy.spin(node) |
| 198 | + except KeyboardInterrupt: |
| 199 | + pass |
| 200 | + finally: |
| 201 | + # Shutdown |
| 202 | + if node.rs_pipeline: |
| 203 | + node.rs_pipeline.stop() |
| 204 | + for cap in node.std_caps: |
| 205 | + cap.release() |
| 206 | + node.destroy_node() |
| 207 | + rclpy.shutdown() |
| 208 | + |
| 209 | +if __name__ == '__main__': |
| 210 | + main() |
0 commit comments