Skip to main content

Mini-Project: Complete Perception Pipeline

Overview​

This mini-project integrates all the concepts covered in Module 3 to create a comprehensive perception pipeline for humanoid robots. You'll implement a complete system that combines synthetic data generation, Isaac ROS perception capabilities, Nav2 navigation, and reinforcement learning control with sim-to-real transfer techniques. This project demonstrates how to build an end-to-end perception and navigation system for humanoid robots.

Learning Objectives​

After completing this mini-project, you will be able to:

  1. Design and implement a complete perception pipeline for humanoid robots
  2. Integrate multiple perception components (detection, segmentation, localization)
  3. Combine perception outputs with navigation and control systems
  4. Implement a reinforcement learning policy that uses perception inputs
  5. Validate the complete system in simulation and evaluate sim-to-real transfer
  6. Deploy the integrated system on a humanoid robot platform

Project Requirements​

Technical Requirements​

  • Implement synthetic data generation using Isaac Sim
  • Integrate Isaac ROS perception nodes for object detection and segmentation
  • Integrate Nav2 for navigation with perception feedback
  • Implement RL-based control that incorporates perception data
  • Include sim-to-real transfer validation
  • Create a complete launch file for the integrated system

Performance Requirements​

  • Perception pipeline should run at 10+ FPS on Jetson Orin
  • Navigation should update at 5+ Hz
  • Overall system should maintain real-time performance
  • Object detection accuracy >85% on validation dataset
  • Navigation success rate >90% in known environments

Deliverables​

  • Complete perception pipeline implementation
  • Training code for synthetic data generation
  • Integration nodes for perception-to-navigation pipeline
  • RL training and deployment code
  • Comprehensive documentation and validation results

System Architecture​

High-Level Architecture​

The complete perception pipeline consists of several integrated components:

┌─────────────────┐    ┌─────────────────────┐    ┌─────────────────┐
│ Isaac Sim │ │ Isaac ROS │ │ Navigation │
│ (Synthetic │───▶│ Perception │───▶│ (Nav2) │
│ Data Gen) │ │ (Detection, │ │ │
└─────────────────┘ │ Segmentation) │ │ │
└─────────────────────┘ └─────────────────┘
│ │
▼ ▼
┌─────────────────────────┐ ┌─────────────────┐
│ Perception Fusion │ │ Control │
│ & Processing │───▶│ (RL Policy) │
│ │ │ │
└─────────────────────────┘ └─────────────────┘
│ │
▼ ▼
┌─────────────────────────────────────────────────┐
│ Humanoid Robot Platform │
│ (Simulation/Real) │
└─────────────────────────────────────────────────┘

Implementation Steps​

Step 1: Synthetic Data Generation Setup​

First, let's set up the synthetic data generation pipeline:

# config/synthetic_data_generation.yaml
dataset_generation:
camera_config:
width: 640
height: 480
fov: 60
fps: 30

lighting_config:
intensity_range: [100, 1000]
color_temperature_range: [3000, 8000]

domain_randomization:
objects:
types: ["human", "chair", "table", "box", "plant"]
count_range: [3, 10]
placement_area: [-5, -5, 5, 5]
materials:
textures: ["wood", "metal", "plastic", "fabric"]
colors: ["red", "blue", "green", "yellow", "gray"]
environment:
floor_materials: ["tile", "wood", "carpet"]
background_objects: ["plants", "artwork", "decorations"]

annotation_config:
bounding_boxes: true
segmentation_masks: true
depth_maps: true
instance_masks: true
# synthetic_data_generator.py
import omni
from pxr import Gf, UsdGeom
import numpy as np
import random
from PIL import Image
import json
import os
from omni.isaac.synthetic_utils import SyntheticDataHelper

class SyntheticDataGenerator:
def __init__(self, config_path):
self.config = self.load_config(config_path)
self.synth_data_helper = SyntheticDataHelper()
self.object_types = self.config['dataset_generation']['domain_randomization']['objects']['types']
self.placement_area = self.config['dataset_generation']['domain_randomization']['objects']['placement_area']

# Initialize output directories
self.output_dir = "synthetic_dataset"
os.makedirs(f"{self.output_dir}/images", exist_ok=True)
os.makedirs(f"{self.output_dir}/annotations", exist_ok=True)
os.makedirs(f"{self.output_dir}/depth", exist_ok=True)

def load_config(self, config_path):
"""Load configuration from YAML file"""
import yaml
with open(config_path, 'r') as f:
return yaml.safe_load(f)

def randomize_scene(self):
"""Randomize the scene for synthetic data generation"""
# Randomize lighting
self.randomize_lighting()

# Randomize materials and textures
self.randomize_materials()

# Randomize object placement
self.randomize_objects()

# Randomize camera parameters
self.randomize_camera()

def randomize_lighting(self):
"""Randomize lighting conditions in the scene"""
# Get all lights in the scene
stage = omni.usd.get_context().get_stage()

for prim in stage.TraverseAll():
if prim.GetTypeName() == "DistantLight" or prim.GetTypeName() == "SphereLight":
# Randomize intensity
intensity = random.uniform(
self.config['dataset_generation']['lighting_config']['intensity_range'][0],
self.config['dataset_generation']['lighting_config']['intensity_range'][1]
)
prim.GetAttribute("intensity").Set(intensity)

# Randomize color based on temperature
color_temp = random.uniform(
self.config['dataset_generation']['lighting_config']['color_temperature_range'][0],
self.config['dataset_generation']['lighting_config']['color_temperature_range'][1]
)
color = self.kelvin_to_rgb(color_temp)
prim.GetAttribute("color").Set(Gf.Vec3f(color[0], color[1], color[2]))

def randomize_materials(self):
"""Randomize materials and textures"""
# This is a simplified implementation
# In practice, you would iterate through materials and assign random textures
pass

def randomize_objects(self):
"""Randomize object placement and properties"""
# Remove existing objects first
self.remove_existing_objects()

# Add random objects
num_objects = random.randint(
self.config['dataset_generation']['domain_randomization']['objects']['count_range'][0],
self.config['dataset_generation']['domain_randomization']['objects']['count_range'][1]
)

for _ in range(num_objects):
self.add_random_object()

def remove_existing_objects(self):
"""Remove objects that are not part of the basic environment"""
# Implementation would remove dynamic objects
pass

def add_random_object(self):
"""Add a random object to the scene"""
# Choose random object type
obj_type = random.choice(self.object_types)

# Generate random position within placement area
x = random.uniform(self.placement_area[0], self.placement_area[2])
y = random.uniform(self.placement_area[1], self.placement_area[3])
z = 0.0 # Height will depend on object

# In a real implementation, you would load and place the object
# This is a simplified placeholder
pass

def kelvin_to_rgb(self, kelvin):
"""Convert temperature in Kelvin to RGB values"""
temp = kelvin / 100
red, green, blue = 0, 0, 0

# Calculate red
if temp <= 66:
red = 255
else:
red = temp - 60
red = 329.698727446 * (red ** -0.1332047592)
red = max(0, min(255, red))

# Calculate green
if temp <= 66:
green = temp
green = 99.4708025861 * np.log(green) - 161.1195681661
else:
green = temp - 60
green = 288.1221695283 * (green ** -0.0755148492)
green = max(0, min(255, green))

# Calculate blue
if temp >= 66:
blue = 255
elif temp <= 19:
blue = 0
else:
blue = temp - 10
blue = 138.5177312231 * np.log(blue) - 305.0447927307
blue = max(0, min(255, blue))

return red/255.0, green/255.0, blue/255.0

def capture_data(self, index):
"""Capture synthetic data for training"""
# Capture RGB image
rgb_data = self.synth_data_helper.get_rgb_data()

# Capture segmentation masks
seg_data = self.synth_data_helper.get_segmentation_data()

# Capture depth data
depth_data = self.synth_data_helper.get_depth_data()

# Save image
img = Image.fromarray(rgb_data)
img_path = f"{self.output_dir}/images/img_{index:06d}.png"
img.save(img_path)

# Save depth
depth_img = Image.fromarray(depth_data)
depth_path = f"{self.output_dir}/depth/depth_{index:06d}.png"
depth_img.save(depth_path)

# Create annotation
annotation = {
'image_path': img_path,
'depth_path': depth_path,
'objects': self.get_object_annotations(),
'camera_intrinsics': self.get_camera_intrinsics()
}

# Save annotation
annot_path = f"{self.output_dir}/annotations/annot_{index:06d}.json"
with open(annot_path, 'w') as f:
json.dump(annotation, f)

def get_object_annotations(self):
"""Get object annotations from the scene"""
# This would extract bounding boxes, segmentation, etc. from the scene
# Implementation would depend on your specific object format
return []

def get_camera_intrinsics(self):
"""Get camera intrinsic parameters"""
# This would return camera intrinsic matrix
return {
'fx': 320, # Focal length in x
'fy': 320, # Focal length in y
'cx': 320, # Principal point x
'cy': 240, # Principal point y
'width': 640,
'height': 480
}

def generate_dataset(self, num_samples=10000):
"""Generate synthetic dataset"""
print(f"Generating {num_samples} synthetic samples...")

for i in range(num_samples):
# Randomize scene
self.randomize_scene()

# Capture data
self.capture_data(i)

if i % 100 == 0:
print(f"Generated {i}/{num_samples} samples")

print(f"Dataset generation complete! Saved to {self.output_dir}")

# Usage example
if __name__ == "__main__":
generator = SyntheticDataGenerator("config/synthetic_data_generation.yaml")
generator.generate_dataset(num_samples=1000) # Adjust as needed

Step 2: Isaac ROS Perception Pipeline​

Now let's implement the Isaac ROS perception pipeline:

# perception_pipeline.py
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image, CameraInfo
from cv_bridge import CvBridge
import cv2
import numpy as np
import torch
import torch.nn as nn
from geometry_msgs.msg import PointStamped
from visualization_msgs.msg import MarkerArray, Marker
from std_msgs.msg import Header

# Isaac ROS specific imports
from isaac_ros_tensor_rt.tensor_rt_engine_tensor_node import TensorRTEngineTensorNode
from isaac_ros_visual_slam import VisualSlamNode

class IsaacPerceptionPipeline(Node):
def __init__(self):
super().__init__('isaac_perception_pipeline')

# Initialize CV bridge
self.bridge = CvBridge()

# Initialize TensorRT models
self.initialize_models()

# Create subscribers
self.image_sub = self.create_subscription(
Image, 'camera/image_raw', self.image_callback, 10)

self.camera_info_sub = self.create_subscription(
CameraInfo, 'camera/camera_info', self.camera_info_callback, 10)

# Create publishers
self.detection_pub = self.create_publisher(
MarkerArray, 'perception/detected_objects', 10)

self.segmentation_pub = self.create_publisher(
Image, 'perception/segmentation', 10)

# Internal state
self.camera_intrinsics = None
self.latest_image = None
self.image_timestamp = None

self.get_logger().info('Isaac Perception Pipeline initialized')

def initialize_models(self):
"""Initialize perception models"""
# Initialize object detection model
self.detection_model = TensorRTEngineTensorNode(
engine_file_path='/models/yolov8.plan',
input_tensor_names=['images'],
input_bindings=['images'],
output_tensor_names=['output0'],
output_bindings=['output0']
)

# Initialize segmentation model
self.segmentation_model = TensorRTEngineTensorNode(
engine_file_path='/models/deeplabv3.plan',
input_tensor_names=['input'],
input_bindings=['input'],
output_tensor_names=['output'],
output_bindings=['output']
)

def camera_info_callback(self, msg):
"""Update camera intrinsics from camera info"""
self.camera_intrinsics = np.array([
[msg.k[0], msg.k[1], msg.k[2]],
[msg.k[3], msg.k[4], msg.k[5]],
[msg.k[6], msg.k[7], msg.k[8]]
]).reshape(3, 3)

def image_callback(self, msg):
"""Process incoming image"""
try:
# Convert ROS image to OpenCV
cv_image = self.bridge.imgmsg_to_cv2(msg, "bgr8")
self.latest_image = cv_image
self.image_timestamp = msg.header.stamp

# Run perception pipeline
detections, segmentation = self.run_perception_pipeline(cv_image)

# Publish results
self.publish_detection_results(detections, msg.header)
self.publish_segmentation_result(segmentation, msg.header)

except Exception as e:
self.get_logger().error(f'Error processing image: {e}')

def run_perception_pipeline(self, image):
"""Run the complete perception pipeline"""
# Preprocess image
det_input = self.preprocess_detection_input(image)
seg_input = self.preprocess_segmentation_input(image)

# Run object detection
detection_results = self.run_detection(det_input)

# Run segmentation
segmentation_results = self.run_segmentation(seg_input)

return detection_results, segmentation_results

def preprocess_detection_input(self, image):
"""Preprocess image for object detection"""
# Resize image
resized = cv2.resize(image, (640, 640))

# Normalize
normalized = resized.astype(np.float32) / 255.0

# Convert HWC to CHW
input_tensor = np.transpose(normalized, (2, 0, 1))

# Add batch dimension
input_tensor = np.expand_dims(input_tensor, axis=0)

return input_tensor

def preprocess_segmentation_input(self, image):
"""Preprocess image for segmentation"""
# Resize image
resized = cv2.resize(image, (513, 513))

# Normalize
normalized = resized.astype(np.float32) / 128.0 - 1.0

# Convert HWC to CHW
input_tensor = np.transpose(normalized, (2, 0, 1))

# Add batch dimension
input_tensor = np.expand_dims(input_tensor, axis=0)

return input_tensor

def run_detection(self, input_tensor):
"""Run object detection"""
try:
# Run inference
results = self.detection_model.infer(input_tensor)

# Process detection results (simplified)
# In reality, you'd parse YOLO outputs properly
return self.parse_detection_results(results[0])
except Exception as e:
self.get_logger().error(f'Error in detection: {e}')
return []

def run_segmentation(self, input_tensor):
"""Run semantic segmentation"""
try:
# Run inference
results = self.segmentation_model.infer(input_tensor)

# Process segmentation results
return self.parse_segmentation_results(results[0])
except Exception as e:
self.get_logger().error(f'Error in segmentation: {e}')
return np.zeros((513, 513), dtype=np.uint8)

def parse_detection_results(self, raw_results):
"""Parse raw detection results"""
# This is a simplified parser - in practice, you'd need to properly decode YOLO outputs
detections = []

# Assuming raw_results contains detection data
# This would need to be adapted based on your actual model output format
if len(raw_results) > 0:
# Example parsing - adjust based on your model
pass

return detections

def parse_segmentation_results(self, raw_results):
"""Parse raw segmentation results"""
# Convert raw results to segmentation mask
# This depends on your model's output format
if len(raw_results.shape) == 4: # (batch, channels, height, width)
# Take argmax to get class predictions
seg_mask = np.argmax(raw_results[0], axis=0)
else:
seg_mask = raw_results

# Resize back to original image size if needed
return seg_mask.astype(np.uint8)

def publish_detection_results(self, detections, header):
"""Publish detection results as markers"""
marker_array = MarkerArray()

for i, detection in enumerate(detections):
marker = Marker()
marker.header = header
marker.ns = "detections"
marker.id = i
marker.type = Marker.CUBE
marker.action = Marker.ADD

# Set position (convert from pixel to 3D if possible)
marker.pose.position.x = detection.get('x', 0.0)
marker.pose.position.y = detection.get('y', 0.0)
marker.pose.position.z = detection.get('z', 1.0) # Default distance

# Set dimensions
marker.scale.x = detection.get('width', 0.5)
marker.scale.y = detection.get('height', 0.5)
marker.scale.z = detection.get('depth', 0.5)

# Set color based on class
class_id = detection.get('class_id', 0)
marker.color = self.get_color_for_class(class_id)
marker.color.a = 0.7 # Transparency

marker_array.markers.append(marker)

self.detection_pub.publish(marker_array)

def publish_segmentation_result(self, segmentation, header):
"""Publish segmentation result as image"""
# Convert segmentation to color image for visualization
color_seg = self.colorize_segmentation(segmentation)

# Convert to ROS image
seg_msg = self.bridge.cv2_to_imgmsg(color_seg, "bgr8")
seg_msg.header = header

self.segmentation_pub.publish(seg_msg)

def get_color_for_class(self, class_id):
"""Get color for a specific class"""
# Define colors for different classes
colors = {
0: (1.0, 0.0, 0.0), # Red - background
1: (0.0, 1.0, 0.0), # Green - person
2: (0.0, 0.0, 1.0), # Blue - chair
3: (1.0, 1.0, 0.0), # Yellow - table
4: (1.0, 0.0, 1.0), # Magenta - other
}

color = colors.get(class_id % len(colors), (0.5, 0.5, 0.5))
return type('Color', (), {'r': color[0], 'g': color[1], 'b': color[2]})()

def colorize_segmentation(self, segmentation):
"""Convert segmentation mask to color image"""
# Create color mappings
color_map = np.array([
[128, 64, 128], # 0 - Road
[244, 35, 232], # 1 - Person
[70, 70, 70], # 2 - Building
[102, 102, 156], # 3 - Wall
[190, 153, 153], # 4 - Fence
[153, 153, 153], # 5 - Pole
[250, 170, 30], # 6 - Traffic Light
[220, 220, 0], # 7 - Traffic Sign
[107, 142, 35], # 8 - Vegetation
[152, 251, 152], # 9 - Terrain
[70, 130, 180], # 10 - Sky
[220, 20, 60], # 11 - Pedestrian
[255, 0, 0], # 12 - Rider
[0, 0, 142], # 13 - Car
[0, 0, 70], # 14 - Truck
[0, 60, 100], # 15 - Bus
[0, 80, 100], # 16 - Train
[0, 0, 230], # 17 - Motorcycle
[119, 11, 32] # 18 - Bicycle
], dtype=np.uint8)

# Map each class to its color
colored_seg = color_map[segmentation % len(color_map)]
return colored_seg

def main(args=None):
rclpy.init(args=args)
perception_pipeline = IsaacPerceptionPipeline()

try:
rclpy.spin(perception_pipeline)
except KeyboardInterrupt:
pass
finally:
perception_pipeline.destroy_node()
rclpy.shutdown()

if __name__ == '__main__':
main()

Step 3: Perception-Fusion Node​

Now let's create a node that fuses perception data with other sensors:

# perception_fusion.py
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image, PointCloud2, Imu, LaserScan
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Point, PointStamped, PoseStamped
from std_msgs.msg import Float32MultiArray, Header
from visualization_msgs.msg import MarkerArray
import numpy as np
import open3d as o3d
from scipy.spatial.transform import Rotation as R
from tf2_ros import TransformListener, Buffer
import tf2_geometry_msgs
import tf_transformations

class PerceptionFusionNode(Node):
def __init__(self):
super().__init__('perception_fusion')

# Initialize internal state
self.latest_camera_pose = None
self.latest_odom = None
self.latest_image = None
self.latest_detections = None
self.latest_segmentation = None

# Initialize TF buffer and listener
self.tf_buffer = Buffer()
self.tf_listener = TransformListener(self.tf_buffer, self)

# Initialize 3D objects list
self.objects_3d = []

# Subscribers for all sensor data
self.detection_sub = self.create_subscription(
MarkerArray, 'perception/detected_objects',
self.detection_callback, 10)

self.segmentation_sub = self.create_subscription(
Image, 'perception/segmentation',
self.segmentation_callback, 10)

self.odom_sub = self.create_subscription(
Odometry, 'odom', self.odom_callback, 10)

self.imu_sub = self.create_subscription(
Imu, 'imu/data', self.imu_callback, 10)

self.scan_sub = self.create_subscription(
LaserScan, 'scan', self.scan_callback, 10)

# Publishers
self.fused_objects_pub = self.create_publisher(
MarkerArray, 'perception/fused_objects', 10)

self.nav_goal_pub = self.create_publisher(
PoseStamped, 'perception/navigation_goals', 10)

# Timer for processing loop
self.process_timer = self.create_timer(0.1, self.process_fusion)

self.get_logger().info('Perception Fusion Node initialized')

def detection_callback(self, msg):
"""Process detection results"""
self.latest_detections = msg

def segmentation_callback(self, msg):
"""Process segmentation results"""
self.latest_segmentation = msg

def odom_callback(self, msg):
"""Process odometry data"""
self.latest_odom = msg
# Update camera pose based on odometry
self.latest_camera_pose = msg.pose.pose

def imu_callback(self, msg):
"""Process IMU data"""
# Could be used for additional orientation refinement
pass

def scan_callback(self, msg):
"""Process laser scan data"""
# Could be used for validation or additional object detection
pass

def process_fusion(self):
"""Process all sensor data and create fused perception"""
if (self.latest_detections is None or
self.latest_odom is None):
return

# Transform 2D detections to 3D world coordinates
world_objects = self.transform_detections_to_world()

# Create fused objects with additional information
fused_objects = self.create_fused_objects(world_objects)

# Publish fused objects
self.publish_fused_objects(fused_objects)

# Generate navigation goals based on perception
self.generate_navigation_goals(fused_objects)

def transform_detections_to_world(self):
"""Transform 2D detections to 3D world coordinates"""
if self.latest_camera_pose is None:
return []

objects_3d = []

# For each detection, create a 3D position
for marker in self.latest_detections.markers:
# Create point in camera frame
camera_point = PointStamped()
camera_point.header = marker.header
camera_point.point.x = marker.pose.position.x
camera_point.point.y = marker.pose.position.y
camera_point.point.z = marker.pose.position.z

try:
# Transform to world frame
world_point = tf2_geometry_msgs.do_transform_point(
camera_point, self.get_transform_to_world())

# Create 3D object
obj_3d = {
'position': [world_point.point.x, world_point.point.y, world_point.point.z],
'type': marker.ns,
'confidence': 0.9, # Placeholder
'bbox': [marker.scale.x, marker.scale.y, marker.scale.z]
}
objects_3d.append(obj_3d)

except Exception as e:
self.get_logger().warn(f'Could not transform detection: {e}')

return objects_3d

def get_transform_to_world(self):
"""Get transform from camera to world frame"""
try:
# Get transform from camera frame to robot base frame
transform = self.tf_buffer.lookup_transform(
'map', # world frame
'camera_link', # camera frame
rclpy.time.Time()) # Use latest available transform
return transform
except Exception as e:
self.get_logger().warn(f'Could not lookup transform: {e}')
return None

def create_fused_objects(self, detected_objects):
"""Create fused objects with additional context"""
fused_objects = []

for obj in detected_objects:
# Get additional information from other sensors
# For example, check if object also detected by LIDAR
obj_context = self.get_object_context(obj)

fused_obj = {
'position': obj['position'],
'type': obj['type'],
'confidence': obj['confidence'],
'bbox': obj['bbox'],
'context': obj_context,
'tracking_id': self.assign_tracking_id(obj)
}
fused_objects.append(fused_obj)

return fused_objects

def get_object_context(self, obj):
"""Get contextual information for an object"""
# Check if object is in path of navigation
# Check if object is static or dynamic (using multiple frames)
# Check if object is traversable (for navigation)

context = {
'is_obstacle': True,
'traversable': False,
'dynamic': False,
'importance': 1.0 # 0-1 scale of importance for navigation
}

# Simplified logic - in practice, this would be more sophisticated
if obj['type'] == 'person':
context['importance'] = 0.9
elif obj['type'] == 'chair':
context['traversable'] = True
context['importance'] = 0.3

return context

def assign_tracking_id(self, obj):
"""Assign or update tracking ID for the object"""
# Simple tracking using position matching
# In practice, use more sophisticated tracking algorithms
min_dist = float('inf')
best_id = -1

for i, existing_obj in enumerate(self.objects_3d):
dist = np.linalg.norm(
np.array(obj['position']) - np.array(existing_obj['position'])
)
if dist < 1.0 and dist < min_dist: # 1m threshold
min_dist = dist
best_id = existing_obj.get('tracking_id', i)

if best_id == -1:
# New object
best_id = len(self.objects_3d)
self.objects_3d.append(obj.copy())
self.objects_3d[-1]['tracking_id'] = best_id
else:
# Update existing object
self.objects_3d[best_id]['position'] = obj['position']

return best_id

def publish_fused_objects(self, fused_objects):
"""Publish fused objects as markers"""
marker_array = MarkerArray()

for i, obj in enumerate(fused_objects):
marker = self.create_object_marker(obj, i)
marker_array.markers.append(marker)

self.fused_objects_pub.publish(marker_array)

def create_object_marker(self, obj, marker_id):
"""Create visualization marker for a fused object"""
marker = Marker()
marker.header.frame_id = 'map'
marker.header.stamp = self.get_clock().now().to_msg()
marker.ns = 'fused_objects'
marker.id = marker_id
marker.type = Marker.CUBE
marker.action = Marker.ADD

# Set position
marker.pose.position.x = obj['position'][0]
marker.pose.position.y = obj['position'][1]
marker.pose.position.z = obj['position'][2]

# Set orientation
marker.pose.orientation.w = 1.0

# Set scale
marker.scale.x = obj['bbox'][0]
marker.scale.y = obj['bbox'][1]
marker.scale.z = obj['bbox'][2]

# Set color based on type
if obj['type'] == 'person':
marker.color.r = 1.0
marker.color.g = 0.0
marker.color.b = 0.0
elif obj['type'] == 'chair':
marker.color.r = 0.0
marker.color.g = 1.0
marker.color.b = 0.0
else:
marker.color.r = 0.0
marker.color.g = 0.0
marker.color.b = 1.0

marker.color.a = 0.8

return marker

def generate_navigation_goals(self, fused_objects):
"""Generate navigation goals based on perception"""
# Find interesting/important objects
interesting_objects = [
obj for obj in fused_objects
if obj['context']['importance'] > 0.5
]

if not interesting_objects:
return

# For each interesting object, create a navigation goal
for obj in interesting_objects:
# Create goal position (approach the object)
goal_pos = obj['position'].copy()

# Adjust to be at a safe distance (e.g., 1 meter away)
# This would involve calculating direction vector from robot to object
if self.latest_odom:
robot_pos = [
self.latest_odom.pose.pose.position.x,
self.latest_odom.pose.pose.position.y,
self.latest_odom.pose.pose.position.z
]

# Calculate vector from robot to object
to_object = np.array(goal_pos) - np.array(robot_pos)
dist = np.linalg.norm(to_object)

if dist > 1.0: # If farther than 1m, move closer
direction = to_object / dist
goal_pos = (np.array(robot_pos) + 1.0 * direction).tolist()

# Create navigation goal message
goal_msg = PoseStamped()
goal_msg.header.frame_id = 'map'
goal_msg.header.stamp = self.get_clock().now().to_msg()
goal_msg.pose.position.x = goal_pos[0]
goal_msg.pose.position.y = goal_pos[1]
goal_msg.pose.position.z = goal_pos[2]

# Set orientation to face the object
if self.latest_odom:
# Simple implementation: orient towards object
dx = goal_pos[0] - robot_pos[0]
dy = goal_pos[1] - robot_pos[1]
yaw = np.arctan2(dy, dx)

quat = tf_transformations.quaternion_from_euler(0, 0, yaw)
goal_msg.pose.orientation.x = quat[0]
goal_msg.pose.orientation.y = quat[1]
goal_msg.pose.orientation.z = quat[2]
goal_msg.pose.orientation.w = quat[3]

# Publish goal
self.nav_goal_pub.publish(goal_msg)

def main(args=None):
rclpy.init(args=args)
fusion_node = PerceptionFusionNode()

try:
rclpy.spin(fusion_node)
except KeyboardInterrupt:
pass
finally:
fusion_node.destroy_node()
rclpy.shutdown()

if __name__ == '__main__':
main()

Step 4: RL Policy Integration​

Now let's implement the RL policy that uses perception data:

# rl_navigation_policy.py
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist, PointStamped, PoseStamped
from sensor_msgs.msg import LaserScan, Image, Imu
from nav_msgs.msg import Odometry
from std_msgs.msg import Float32MultiArray
from visualization_msgs.msg import MarkerArray
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import deque
import random

class NavigationRLObservationProcessor:
"""Process various sensor inputs for RL policy"""

def __init__(self):
self.laser_ranges = None
self.odom_data = None
self.perception_objects = {}
self.imu_data = None

# Observation parameters
self.laser_beams = 720 # Number of laser beams to use
self.laser_range = 10.0 # Maximum laser range to consider
self.object_history_size = 10 # Number of timesteps to remember objects
self.ego_history_size = 5 # Number of timesteps for ego motion history

def process_observation(self):
"""Process all sensor data into RL observation vector"""
obs_parts = []

# Add processed laser scan
laser_obs = self.process_laser_scan()
obs_parts.append(laser_obs)

# Add odometry information
odom_obs = self.process_odometry()
obs_parts.append(odom_obs)

# Add perception-based object information
obj_obs = self.process_objects()
obs_parts.append(obj_obs)

# Add IMU data
imu_obs = self.process_imu()
obs_parts.append(imu_obs)

# Concatenate all observations
full_obs = np.concatenate(obs_parts)

# Normalize observation
normalized_obs = self.normalize_observation(full_obs)

return normalized_obs

def process_laser_scan(self):
"""Process laser scan data"""
if self.laser_ranges is None:
# Return zeros if no laser data
return np.zeros(self.laser_beams)

# Take every nth beam to get desired number of beams
step = len(self.laser_ranges) // self.laser_beams
processed_scan = []

for i in range(0, len(self.laser_ranges), step):
range_val = self.laser_ranges[i]
# Normalize to [0, 1] range
norm_range = min(range_val, self.laser_range) / self.laser_range
processed_scan.append(norm_range)

return np.array(processed_scan)

def process_odometry(self):
"""Process odometry data"""
if self.odom_data is None:
return np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) # [x, y, z, vx, vy, vz]

pos = self.odom_data.pose.pose.position
vel = self.odom_data.twist.twist.linear

return np.array([
pos.x, pos.y, pos.z,
vel.x, vel.y, vel.z
])

def process_objects(self):
"""Process perception objects"""
# Simple representation: closest object distance and type
if not self.perception_objects:
# Return zeros if no objects detected
return np.zeros(5) # [dist, angle, type_encoded, is_person, is_obstacle]

# Find closest object
closest_obj = min(self.perception_objects, key=lambda x: np.linalg.norm(x['position']))

# Calculate relative position
rel_x = closest_obj['position'][0]
rel_y = closest_obj['position'][1]
dist = np.sqrt(rel_x**2 + rel_y**2)
angle = np.arctan2(rel_y, rel_x)

# Encode object type
is_person = 1.0 if closest_obj['type'] == 'person' else 0.0
is_obstacle = 1.0 if closest_obj.get('context', {}).get('is_obstacle', False) else 0.0

return np.array([
min(dist, 10.0) / 10.0, # Normalized distance
angle / np.pi, # Normalized angle
0.0, # Placeholder for more complex type encoding
is_person,
is_obstacle
])

def process_imu(self):
"""Process IMU data"""
if self.imu_data is None:
return np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) # [angular_velocities, linear_accel]

av = self.imu_data.angular_velocity
la = self.imu_data.linear_acceleration

return np.array([
av.x, av.y, av.z,
la.x, la.y, la.z
])

def normalize_observation(self, obs):
"""Normalize observation to [-1, 1] range"""
# This is a simple normalization - in practice you'd use learned statistics
# or domain knowledge to set appropriate ranges
return np.clip(obs, -10, 10) / 10

class PPOActorCritic(nn.Module):
"""Actor-Critic network for navigation policy"""

def __init__(self, obs_dim, action_dim, hidden_dim=256):
super(PPOActorCritic, self).__init__()

# Shared feature extraction layers
self.shared_layers = nn.Sequential(
nn.Linear(obs_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU()
)

# Actor head (for action selection)
self.actor_mean = nn.Linear(hidden_dim, action_dim)
self.actor_std = nn.Parameter(torch.ones(action_dim) * 0.1)

# Critic head (for value estimation)
self.critic = nn.Linear(hidden_dim, 1)

def forward(self, obs):
features = self.shared_layers(obs)

# Actor
action_mean = torch.tanh(self.actor_mean(features))

# Critic
value = self.critic(features)

return action_mean, self.actor_std, value

def get_action(self, obs):
"""Sample action from policy"""
action_mean, action_std, value = self.forward(obs)

# Create distribution
dist = torch.distributions.Normal(action_mean, action_std)
action = dist.sample()
log_prob = dist.log_prob(action).sum(dim=-1)

return action, log_prob, value

def evaluate_action(self, obs, action):
"""Evaluate action for training"""
action_mean, action_std, value = self.forward(obs)

dist = torch.distributions.Normal(action_mean, action_std)
log_prob = dist.log_prob(action).sum(dim=-1)
entropy = dist.entropy().sum(dim=-1)

return log_prob, value, entropy

class RLNavigationPolicy(Node):
"""Reinforcement Learning Navigation Policy Node"""

def __init__(self):
super().__init__('rl_navigation_policy')

# Initialize observation processor
self.obs_processor = NavigationRLObservationProcessor()

# Define action space: [linear_vel, angular_vel]
self.action_dim = 2
self.obs_dim = (self.obs_processor.laser_beams + 6 + 5 + 6) # laser + odom + objects + imu

# Initialize policy network
self.policy_network = PPOActorCritic(self.obs_dim, self.action_dim)

# Load trained model if available
self.load_model()

# Episode tracking
self.current_episode_data = deque(maxlen=1000) # Store recent transitions

# ROS publishers and subscribers
self.cmd_vel_pub = self.create_publisher(Twist, 'cmd_vel', 10)

self.laser_sub = self.create_subscription(
LaserScan, 'scan', self.laser_callback, 10)

self.odom_sub = self.create_subscription(
Odometry, 'odom', self.odom_callback, 10)

self.imu_sub = self.create_subscription(
Imu, 'imu/data', self.imu_callback, 10)

self.perception_sub = self.create_subscription(
MarkerArray, 'perception/fused_objects', self.perception_callback, 10)

# Goal subscriber
self.goal_sub = self.create_subscription(
PoseStamped, 'perception/navigation_goals', self.goal_callback, 10)

# Control timer
self.control_timer = self.create_timer(0.1, self.control_loop)

# Internal state
self.current_goal = None
self.current_action = None
self.last_observation = None

self.get_logger().info('RL Navigation Policy initialized')

def load_model(self):
"""Load trained model"""
model_path = 'models/navigation_policy.pth'
try:
checkpoint = torch.load(model_path, map_location='cpu')
self.policy_network.load_state_dict(checkpoint['model_state_dict'])
self.get_logger().info(f'Loaded model from {model_path}')
except FileNotFoundError:
self.get_logger().info('No trained model found, using random initialization')

def laser_callback(self, msg):
"""Process laser scan data"""
self.obs_processor.laser_ranges = np.array(msg.ranges)

def odom_callback(self, msg):
"""Process odometry data"""
self.obs_processor.odom_data = msg

def imu_callback(self, msg):
"""Process IMU data"""
self.obs_processor.imu_data = msg

def perception_callback(self, msg):
"""Process perception data"""
objects = []
for marker in msg.markers:
obj = {
'position': [marker.pose.position.x, marker.pose.position.y, marker.pose.position.z],
'type': marker.ns,
'id': marker.id
}
objects.append(obj)

self.obs_processor.perception_objects = objects

def goal_callback(self, msg):
"""Process navigation goal"""
self.current_goal = msg.pose
self.get_logger().info(f'Received new navigation goal: {msg.pose.position}')

def control_loop(self):
"""Main control loop"""
# Get current observation
obs = self.obs_processor.process_observation()
obs_tensor = torch.FloatTensor(obs).unsqueeze(0)

# Get action from policy
with torch.no_grad():
action, _, _ = self.policy_network.get_action(obs_tensor)
action = action.cpu().numpy()[0]

# Convert action to velocity command
cmd_vel = Twist()
cmd_vel.linear.x = np.clip(action[0], -1.0, 1.0) * 0.5 # Scale down
cmd_vel.angular.z = np.clip(action[1], -1.0, 1.0) * 0.5 # Scale down

# Publish command
self.cmd_vel_pub.publish(cmd_vel)

# Store transition for potential training
if self.last_observation is not None:
transition = {
'obs': self.last_observation,
'action': self.current_action,
'next_obs': obs,
'reward': self.calculate_reward(), # Simplified
'done': False
}
self.current_episode_data.append(transition)

# Update internal state
self.last_observation = obs
self.current_action = action

def calculate_reward(self):
"""Calculate reward for current state"""
# Simplified reward calculation
# In practice, this would be more complex
reward = 0.0

# Reward forward movement
if self.obs_processor.odom_data:
lin_vel = self.obs_processor.odom_data.twist.twist.linear
reward += lin_vel.x * 0.1 # Small reward for forward movement

# Penalty for collision risk
if self.obs_processor.laser_ranges is not None:
min_dist = min(self.obs_processor.laser_ranges) if self.obs_processor.laser_ranges else float('inf')
if min_dist < 0.5:
reward -= 1.0 # Penalty for being too close to obstacles

return reward

def main(args=None):
rclpy.init(args=args)
policy_node = RLNavigationPolicy()

try:
rclpy.spin(policy_node)
except KeyboardInterrupt:
pass
finally:
policy_node.destroy_node()
rclpy.shutdown()

if __name__ == '__main__':
main()

Step 5: Complete Launch File​

Now let's create the complete launch file to bring up the entire system:

<!-- launch/perception_pipeline.launch.py -->
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
from launch.launch_description_sources import PythonLaunchDescriptionSource

def generate_launch_description():
# Declare launch arguments
use_sim_time = LaunchConfiguration('use_sim_time')
robot_namespace = LaunchConfiguration('robot_namespace')

return LaunchDescription([
# Declare launch arguments
DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use simulation clock if true'),

DeclareLaunchArgument(
'robot_namespace',
default_value='',
description='Robot namespace for multi-robot deployments'),

# Include Isaac ROS perception nodes
IncludeLaunchDescription(
PythonLaunchDescriptionSource([
PathJoinSubstitution([
FindPackageShare('isaac_ros_visual_slam'),
'launch', 'visual_slam.launch.py'
])
]),
launch_arguments={
'use_sim_time': use_sim_time,
'enable_occupancy_map': 'True'
}.items()
),

# Perception pipeline node
Node(
package='physical_ai_humanoid',
executable='perception_pipeline',
name='isaac_perception_pipeline',
parameters=[
{'use_sim_time': use_sim_time}
],
remappings=[
('camera/image_raw', 'camera/image_rect_raw'),
('camera/camera_info', 'camera_info')
]
),

# Perception fusion node
Node(
package='physical_ai_humanoid',
executable='perception_fusion',
name='perception_fusion',
parameters=[
{'use_sim_time': use_sim_time}
]
),

# RL navigation policy
Node(
package='physical_ai_humanoid',
executable='rl_navigation_policy',
name='rl_navigation_policy',
parameters=[
{'use_sim_time': use_sim_time}
]
),

# Nav2 stack (if needed for comparison)
IncludeLaunchDescription(
PythonLaunchDescriptionSource([
PathJoinSubstitution([
FindPackageShare('nav2_bringup'),
'launch', 'navigation_launch.py'
])
]),
launch_arguments={
'use_sim_time': use_sim_time
}.items()
),
])

Step 6: Validation and Testing​

Let's create a validation node to test the complete system:

# validation_node.py
import rclpy
from rclpy.node import Node
from std_msgs.msg import Float32MultiArray
from geometry_msgs.msg import PoseStamped, Twist
from visualization_msgs.msg import MarkerArray
from nav_msgs.msg import Odometry
import numpy as np
import time

class PerceptionPipelineValidator(Node):
def __init__(self):
super().__init__('perception_pipeline_validator')

# Subscribe to all relevant topics
self.fused_objects_sub = self.create_subscription(
MarkerArray, 'perception/fused_objects',
self.fused_objects_callback, 10)

self.odom_sub = self.create_subscription(
Odometry, 'odom',
self.odom_callback, 10)

self.cmd_vel_sub = self.create_subscription(
Twist, 'cmd_vel',
self.cmd_vel_callback, 10)

# Metrics tracking
self.metrics = {
'object_detection_rate': 0.0,
'perception_accuracy': 0.0,
'navigation_efficiency': 0.0,
'system_latency': 0.0
}

self.object_count = 0
self.last_object_time = time.time()
self.odom_history = []
self.cmd_vel_history = []

# Validation timer
self.validation_timer = self.create_timer(1.0, self.run_validation)

self.get_logger().info('Perception Pipeline Validator initialized')

def fused_objects_callback(self, msg):
"""Count detected objects for validation"""
self.object_count += len(msg.markers)
self.last_object_time = time.time()

def odom_callback(self, msg):
"""Track robot motion"""
self.odom_history.append({
'time': time.time(),
'position': [msg.pose.pose.position.x, msg.pose.pose.position.y],
'velocity': [msg.twist.twist.linear.x, msg.twist.twist.linear.y]
})

# Keep only recent history
if len(self.odom_history) > 100:
self.odom_history = self.odom_history[-50:]

def cmd_vel_callback(self, msg):
"""Track control commands"""
self.cmd_vel_history.append({
'time': time.time(),
'linear': msg.linear.x,
'angular': msg.angular.z
})

if len(self.cmd_vel_history) > 100:
self.cmd_vel_history = self.cmd_vel_history[-50:]

def run_validation(self):
"""Run validation and print metrics"""
# Calculate object detection rate (objects per second)
current_time = time.time()
time_elapsed = current_time - self.last_object_time if hasattr(self, 'last_object_time') else 1.0
if time_elapsed > 0:
detection_rate = self.object_count / time_elapsed if self.object_count > 0 else 0.0
self.metrics['object_detection_rate'] = detection_rate

# Calculate navigation efficiency (simplified)
if len(self.odom_history) > 1:
total_distance = 0.0
for i in range(1, len(self.odom_history)):
pos1 = self.odom_history[i-1]['position']
pos2 = self.odom_history[i]['position']
dist = np.sqrt((pos2[0]-pos1[0])**2 + (pos2[1]-pos1[1])**2)
total_distance += dist

avg_speed = total_distance / len(self.odom_history) if self.odom_history else 0.0
self.metrics['navigation_efficiency'] = avg_speed

# Print current metrics
self.get_logger().info(
f"Validation Metrics:\n"
f" Object Detection Rate: {self.metrics['object_detection_rate']:.2f} Hz\n"
f" Navigation Efficiency: {self.metrics['navigation_efficiency']:.3f} m/s\n"
)

# Reset object counter
self.object_count = 0
self.last_object_time = time.time()

def main(args=None):
rclpy.init(args=args)
validator = PerceptionPipelineValidator()

try:
rclpy.spin(validator)
except KeyboardInterrupt:
pass
finally:
validator.destroy_node()
rclpy.shutdown()

if __name__ == '__main__':
main()

Testing and Integration​

Testing Plan​

  1. Unit Testing:

    • Test each component independently
    • Validate data flow between components
    • Verify model loading and inference
  2. Integration Testing:

    • Test complete pipeline with simulated data
    • Verify perception-accurate navigation
    • Check RL policy behavior
  3. System Testing:

    • End-to-end testing in simulation
    • Performance validation
    • Robustness testing

Performance Evaluation​

# evaluation_metrics.py
import numpy as np

class PerceptionPipelineEvaluator:
def __init__(self):
self.metrics = {
'perception_accuracy': [],
'navigation_success_rate': [],
'computation_time': [],
'power_consumption': [],
}

def calculate_perception_accuracy(self, predictions, ground_truth):
"""Calculate perception accuracy metrics"""
# Calculate IoU for detection
# Calculate mAP (mean Average Precision)
# Calculate segmentation accuracy

if len(predictions) == 0 and len(ground_truth) == 0:
return 1.0 # Perfect if both empty

if len(predictions) == 0 or len(ground_truth) == 0:
return 0.0 # No match if one is empty

# Simplified accuracy calculation
correct_detections = 0
total_detections = len(ground_truth)

for gt_obj in ground_truth:
for pred_obj in predictions:
if self.is_match(gt_obj, pred_obj):
correct_detections += 1
break

return correct_detections / total_detections if total_detections > 0 else 0.0

def is_match(self, gt_obj, pred_obj):
"""Check if ground truth and prediction match"""
# Calculate IoU or distance threshold
gt_pos = np.array(gt_obj['position'])
pred_pos = np.array(pred_obj['position'])

dist = np.linalg.norm(gt_pos - pred_pos)
return dist < 0.5 # 50cm threshold

def calculate_navigation_success_rate(self, goals, successes):
"""Calculate navigation success rate"""
if len(goals) == 0:
return 0.0
return sum(successes) / len(goals)

def evaluate_pipeline(self, test_episodes=10):
"""Run comprehensive evaluation"""
results = []

for episode in range(test_episodes):
episode_result = self.run_episode_evaluation()
results.append(episode_result)

# Calculate aggregate metrics
avg_accuracy = np.mean([r['accuracy'] for r in results])
avg_success = np.mean([r['success_rate'] for r in results])
avg_time = np.mean([r['computation_time'] for r in results])

return {
'average_perception_accuracy': avg_accuracy,
'average_navigation_success': avg_success,
'average_computation_time': avg_time,
'detailed_results': results
}

def run_episode_evaluation(self):
"""Run evaluation for a single episode"""
# This would execute the pipeline and record metrics
# In practice, this would interface with the actual pipeline
return {
'accuracy': np.random.random(), # Placeholder
'success_rate': np.random.random(), # Placeholder
'computation_time': np.random.random() * 0.1, # Placeholder
'power_draw': np.random.random() * 50 # Placeholder
}

# Example usage
def run_evaluation():
evaluator = PerceptionPipelineEvaluator()
results = evaluator.evaluate_pipeline(test_episodes=5)

print("Evaluation Results:")
print(f"Average Perception Accuracy: {results['average_perception_accuracy']:.3f}")
print(f"Average Navigation Success: {results['average_navigation_success']:.3f}")
print(f"Average Computation Time: {results['average_computation_time']:.4f}s")

if __name__ == "__main__":
run_evaluation()

Deployment Considerations​

Hardware Optimizations​

For deployment on humanoid robot platforms:

  1. Edge Computing Setup:

    • Configure Jetson Orin for optimal performance
    • Optimize TensorRT models for target hardware
    • Configure power management settings
  2. Real-time Performance:

    • Set CPU affinity for perception nodes
    • Configure real-time priority
    • Optimize memory usage
  3. Sensing Pipeline Optimization:

    • Use hardware-accelerated image processing
    • Optimize sensor data rates
    • Implement data buffering and synchronization

Troubleshooting Notes​

  1. Memory Issues: Monitor GPU memory usage and optimize model sizes if needed.

  2. Timing Problems: Ensure all nodes operate at consistent rates to maintain real-time performance.

  3. Sensor Synchronization: Use message filters to properly synchronize data from different sensors.

  4. Model Accuracy: Validate that synthetic training data adequately represents real-world scenarios.

Summary​

This mini-project demonstrates the integration of multiple perception components into a complete pipeline for humanoid robots. The system combines synthetic data generation, Isaac ROS perception capabilities, perception fusion, and reinforcement learning-based navigation into a cohesive framework. The implementation provides a foundation for building more sophisticated perception and navigation systems for humanoid robots.

Next Steps​

With this complete perception pipeline, you have implemented a sophisticated system that can be extended with additional capabilities such as:

  • Advanced manipulation planning based on perception
  • Human-robot interaction using vision and audio
  • More complex navigation behaviors
  • Learning from demonstration and reinforcement learning
  • Integration with higher-level task planners

References​

  1. Isaac ROS Documentation: https://nvidia-isaac-ros.github.io/
  2. ROS Navigation Stack: http://wiki.ros.org/navigation
  3. Deep Learning for Robotics: https://arxiv.org/abs/1901.03039
  4. Perception for Mobile Robots: https://mitpress.mit.edu/books/perception-mobile-robots
  5. Reinforcement Learning in Robotics: https://ieeexplore.ieee.org/document/8794198
💬
🤖
ROBO-ASSISTANT
Hello! I'm your AI assistant for Physical AI & Humanoid Robotics. How can I help you today?