Integrating AI Models into ROS 2: A Technical Guide

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1566 services
Integrating AI Models into ROS 2: A Technical Guide
Medium
~2-4 weeks
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1318
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1226
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    926
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1158
  • image_logo-advance_0.webp
    B2B Advance company logo design
    620
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    894

Integrating AI Models into ROS 2: A Technical Guide

A client came with an UGV based on ROS 2 Humble: a stereo depth pair, a Velodyne VLP-16 LiDAR, and a Jetson Orin NX. The requirement was object detection at 30 Hz, but PyTorch YOLOv8 straight out of the box delivered only 12 FPS. The problem: CPU-bound due to OpenCV conversion and a blocking callback executor. Here's how we rewrote the node architecture and squeezed out 125 FPS.

This guide covers ROS AI integration, object detection in ROS, YOLOv8 with ROS 2, PointNet for LiDAR in ROS, RL navigation in ROS, and TensorRT optimization for real-time inference. We focus on NVIDIA Jetson AI platform for robotics AI. Our AI nodes for ROS 2 are designed for minimal latency. We also provide ML integration with ROS and custom AI model development for ROS.

Our team has specialized in integrating AI models into ROS 2 for over 7 years. We've learned to circumvent typical issues: latency, bus overload, framework incompatibility. Below are real cases and proven solutions.

How does ROS 2 + AI architecture work?

An AI model in ROS 2 is a Node subscribed to sensor topics and publishing results. Key point: do not block the callback executor. We design the node so that inference runs in a separate thread, and publishing happens via a publisher.

import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from vision_msgs.msg import Detection2DArray
from cv_bridge import CvBridge
import torch
import numpy as np

class ObjectDetectionNode(Node):
    def __init__(self):
        super().__init__('object_detection')
        self.model = torch.hub.load('ultralytics/yolov8', 'yolov8n', pretrained=True)
        self.model.eval()
        if torch.cuda.is_available():
            self.model.cuda()
        self.bridge = CvBridge()
        self.subscription = self.create_subscription(Image, '/camera/color/image_raw', self.image_callback, 10)
        self.detection_pub = self.create_publisher(Detection2DArray, '/detections', 10)
        self.get_logger().info('Object detection node started')

    def image_callback(self, msg: Image):
        cv_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding='rgb8')
        with torch.no_grad():
            results = self.model(cv_image)
        detections = self._to_detection_array(results, msg.header)
        self.detection_pub.publish(detections)

How to implement LiDAR + PointNet for 3D perception?

For 3D scenes we use PointNet. LiDAR data in PointCloud2 format is converted to numpy, subsampled to 1024 points, and fed into the model.

from sensor_msgs.msg import PointCloud2
import sensor_msgs_py.point_cloud2 as pc2

class LidarPerceptionNode(Node):
    def __init__(self):
        super().__init__('lidar_perception')
        self.pointnet_model = load_pointnet_model('pointnet_weights.pth')
        self.sub = self.create_subscription(PointCloud2, '/velodyne_points', self.lidar_callback, 10)

    def lidar_callback(self, msg: PointCloud2):
        points = np.array(list(pc2.read_points(msg, field_names=("x","y","z"))))
        indices = np.random.choice(len(points), 1024, replace=False)
        sampled = points[indices]
        tensor = torch.FloatTensor(sampled).unsqueeze(0).cuda()
        with torch.no_grad():
            classes = self.pointnet_model(tensor)

How to achieve 30 Hz real-time performance?

Latency is the main enemy of real-time. Standard PyTorch on Jetson Orin delivers ~45 ms (22 Hz). Our experience: TensorRT (see NVIDIA official documentation) gives 3-5x speedup — down to 8 ms (125 Hz). TensorRT INT8 delivers up to 5.6x speedup compared to standard PyTorch FP32. We also leverage NVIDIA's DLA and Tensor Cores for extra acceleration, and use CUDA graphs to reduce kernel launch overhead. Additionally:

  • Parallel inference in a separate thread (does not block the executor)
  • CUDA streams for processing multiple frames
  • INT8 quantization with calibration on a representative dataset
Method Latency (Jetson Orin) FPS
PyTorch (FP32) ~45 ms 22
ONNX Runtime (FP32) ~25 ms 40
TensorRT (FP16) ~12 ms 83
TensorRT (INT8) ~8 ms 125

Comparison of Approaches: Accuracy vs Speed

TensorRT in INT8 provides a 5.6x speedup with only 2% accuracy loss — ideal for real-time.

Model mAP@50 Latency (Jetson Orin) FPS
YOLOv8n (FP32) 0.59 45 ms 22
YOLOv8n (TensorRT INT8) 0.57 8 ms 125
YOLOv8m (TensorRT INT8) 0.62 15 ms 67

What is included in navigation with RL policy?

from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry

class RLNavigationNode(Node):
    def __init__(self):
        super().__init__('rl_navigation')
        self.policy = load_stable_baselines3_model('navigation_policy.zip')
        self.cmd_vel_pub = self.create_publisher(Twist, '/cmd_vel', 10)
        self.odom_sub = self.create_subscription(Odometry, '/odom', self.step, 10)

    def step(self, odom_msg):
        state = self._odom_to_state(odom_msg)
        action, _ = self.policy.predict(state, deterministic=True)
        cmd = Twist()
        cmd.linear.x = float(action[0])
        cmd.angular.z = float(action[1])
        self.cmd_vel_pub.publish(cmd)

The policy was trained in a simulator (Isaac Gym) and transferred to a real robot. In our experience, fine-tuning on real data reduces the sim-to-real gap by 40%.

How to monitor AI nodes?

The performance of an AI node in ROS 2 must be monitored in real time. We embed the following tools:

  • Diagnostic topics: /diagnostics publishes inference latency, FPS, and GPU load every 1 second standard with ROS 2 diagnostic_msgs.
  • Prometheus + Grafana: we export custom metrics via the prometheus_client Python library. The dashboard shows p50/p95/p99 latency percentiles over a sliding 5-minute window.
  • Rosbag recording: critical incidents (latency > 2× baseline) are automatically recorded to rosbag for analysis.
  • Data drift: input pixel/point distributions are compared to the training dataset using the KS-test. Alert when p-value < 0.05 — a signal of detection quality degradation.

Such observability allows us to detect model degradation before it affects the robot's mission.

What is the work process?

  1. Analysis: break down the latency budget, select the model, profile.
  2. Design: node architecture, topic schema, QoS.
  3. Implementation: write C++/Python code, integrate with TensorRT/ONNX.
  4. Testing: simulation (Gazebo + pixel racing) and real hardware.
  5. Deployment: containerization with Docker, ROS 2 Launch files, monitoring.

Typical integration mistakes

  • Forgetting to set QoS depth: at 30 FPS, 10 is sufficient; otherwise queue overflow.
  • Using a single thread for inference and callbacks — leads to drops.
  • Not profiling image conversion: cv_bridge can take up to 30% of the time.
  • Ignoring the calibration dataset for INT8 — accuracy drops by 10%+.

Why work with us?

We are a team of AI/ML engineers with 7+ years of experience in robotics. Over 30 successful AI integrations into ROS (from autonomous drones to industrial manipulators). We guarantee stable perception pipeline performance on the target platform. Our projects start at $5,000 and typically save clients 30% on development time. Evaluate your project — get a consultation. Integration takes from 2 to 4 weeks, cost is calculated individually.

Contact us to discuss your task — we will help you choose the optimal configuration.