Integrate ROS2 + YOLO: package object detection as a node
Atlasbot · 18/8/2026 · 12 min read
Being able to run YOLO independently on an image/video file is a start (learned in What is YOLO? ) — but for real use in robotics, the identification results need to become part of the ROS2 system: read images directly from the camera node, and publish the results into a topic for other nodes (Nav2 avoiding dynamic obstacle, monitoring node...) to use.
Key concepts
camera node (v4l2_camera) → topic /image_raw
│
▼
YOLO detection node (newly written)
│
▼
topic /detections (bounding boxes + labels)
YOLO nodes serve both as subscribers (receiving images from cameras) and publisher (sending detection results) — common designs for every "processing and forwarding" node in ROS2, exactly the role of a node in ROS2 Layer learned at ROS2 Layer in AMR.
How it works
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
from ultralytics import YOLO
class YoloDetectionNode(Node):
def __init__(self):
super().__init__("yolo_detection_node")
self.model = YOLO("yolov8n.pt")
self.bridge = CvBridge()
self.subscription = self.create_subscription(
Image, "/image_raw", self.image_callback, 10
)
# real-world should publish sensor msgs/Image (drawn box) or
# vision_msgs/Detection2DArray instead of self-define
self.publisher = self.create_publisher(Image, "/detections/image", 10)
def image_callback(self, msg):
frame = self.bridge.imgmsg_to_cv2(msg, desired_encoding="bgr8")
results = self.model(frame, verbose=False)
annotated = results[0].plot() # pre-drawn bounding box on image
out_msg = self.bridge.cv2_to_imgmsg(annotated, encoding="bgr8")
self.publisher.publish(out_msg)
def main():
rclpy.init()
node = YoloDetectionNode()
rclpy.spin(node)
cv_bridge is a package for the back-and-forth conversion between OpenCV-formal images (numpy array) and ROS2 message (sensor_msgs/Image) — bridges that are required every time processing ROS2 images with OpenCV/AI-models, in the correct preprocessing step learned in the basic OpenCV lesson.
Technical details
Formulas
Running AI inference per camera frame (typically 30 frames per second) can exceed the processing capabilities of embedded computers, causing a blockage (backlog) callback — estimate of the number of missed frames:
If Inference_time > Camera_frame_period:
Backlogged_frames_per_second ≈ FPS_camera − (1/Inference_time)
Example: 30fps camera (33ms period), inference takes 100ms/frame (CPU only)
Processing_FPS ≈ 1/0.1 = 10fps
Backlogged_frames ≈ 30 − 10 = 20 frames/second queued or skipped
→ Limit processing frequency or use QoS depth=1 to always take the latest frame
instead of processing outdated frames sequentially
Parameters
| Handling | Advantages | Disadvantages |
|---|---|---|
| All frames processed (no limit) | Do not omit data | Easy congestion if inference is slower than camera |
| Limited frequency (e.g., every 3 - 5 frames) | Reduce computational load | Ignore frames between sessions |
| QoS depth=1 | Always process the latest frames | Skip old frames completely, do not process sequentially |
Practical applications
Common processing practices in the real-world: limit processing frequency (e.g., run YOLO every 3 - 5 frames instead of every frame), or use qos_profile with depth=1 to automatically skip old frames when the processing node fails, always preferring to process the latest frame — strictly according to the QoS principle for high frequency sensor data learned at the ROS2 Layer in AMR (prioritizing the latest data over ensuring that all old messages are received).
Practical example
class YoloDetectionNode(Node):
def __init__(self):
super().__init__("yolo_detection_node")
self.model = YOLO("yolov8n.pt")
self.bridge = CvBridge()
self.frame_count = 0
self.SKIP_FRAMES = 3 # only process 1/3 frames
self.subscription = self.create_subscription(
Image, "/image_raw", self.image_callback, 10
)
self.publisher = self.create_publisher(Image, "/detections/image", 10)
def image_callback(self, msg):
self.frame_count += 1
if self.frame_count % self.SKIP_FRAMES != 0:
return # skip this frame to reduce computation
frame = self.bridge.imgmsg_to_cv2(msg, desired_encoding="bgr8")
results = self.model(frame, verbose=False)
annotated = results[0].plot()
out_msg = self.bridge.cv2_to_imgmsg(annotated, encoding="bgr8")
self.publisher.publish(out_msg)
With a 30fps camera and SKIP_FRAMES=3:
Actual processing frequency ≈ 30/3 = 10fps
Enough for many obstacle detection applications (no need to respond at 30fps),
while reducing computational load by 3 times compared with processing every frame
Common mistakes
- Handling of all frames on hardware is not fast enough— as calculated in the Formulary, causing callback stagnation, latency increasing with time instead of stability.
- Not using
cv_bridgebut self-written image transform — prone to malformed encoding format (BGR/RGB, learned in Basic OpenCV),cv_bridgecorrectly dealt with common cases. - Publish detection results as box drawn images instead of structured data— limits the ability of other nodes (Nav2, application logic) to use programmatic detection results;
vision_msgs/Detection2DArrayshould be considered for directly usable structured data. - No limit on frequency processed when hardware is not sufficiently robust — leads to the calculated phenomenon in the Formulary, increasing latency, affecting also other nodes waiting for data from the YOLO node.
Conclusion
The integration of YOLO into ROS2 is essentially just a conventional subscriber/publisher node, with cv_bridge bridging between OpenCV image data and ROS2 messages. The most important consideration when implementing a real-world implementation is the performance management — ensuring that the AI pipeline does not jam other nodes that are in need of real - time data, either by limiting processing frequency or using QoS accordingly. This is the last article of Sensor & Perception — from LiDAR, Camera, IMU, to Computer Vision/AI, the entire platform sensors of an AMR have been fully presented, ready to be merged into the hardware and software architectures learned in the AMR/AGV section.
Get new articles and lessons by email
When a new technical article or course module is published, Atlas Robotics sends you a short email. No spam.
Unsubscribe any time with the link in each email. See our Privacy policy.