10 · Object detection with YOLO¶
Goal. Detect everyday objects in the Lime's camera images with YOLO. The detector is an ordinary ROS 2 node: it does not know, or care, that the images come from a simulator.

/detections/image: YOLO11n finds the bowl, the cup, the banana and the bottle that tutorial 08's camera sees.Concepts¶
flowchart LR
subgraph ISAAC[Isaac Sim]
cam[D435 camera<br/>tutorial 08]
end
subgraph ROS[ROS 2 container]
yolo[lime_yolo/yolo_detector<br/>Ultralytics YOLO11n, CPU]
end
cam -- "/camera/camera/color/image_raw" --> yolo
yolo -- "/detections<br/>vision_msgs/Detection2DArray" --> app[your node]
yolo -- "/detections/image" --> view[rqt_image_view / RViz]
- YOLO ("You Only Look Once") is a family of real-time object detectors. The pretrained models know the 80 everyday classes of the COCO dataset: cup, bowl, banana, bottle, chair, person, …. The lime_room objects were chosen from those classes.
vision_msgs/Detection2DArrayis the standard ROS message for 2D detections: one entry per object, with its box (centre and size in pixels) and a class name with a score.- The node processes only the newest image, at most 5 times per second. On a CPU that is enough for a demo, and the simulation never waits for it.
License
The tutorial code is Apache-2.0. Ultralytics YOLO is AGPL-3.0: it is installed in the Docker image and the
model weights are downloaded at first use (to ~/.cache/lime_yolo in the container). Neither is part of this
repository. Check the license before you use it in a product. NVIDIA's
Isaac ROS isaac_ros_yolov8
is a GPU-accelerated (TensorRT) alternative for advanced users.
Run it¶
Terminal 1, Isaac Sim (the same scene as tutorial 08):
Terminal 2, the detector (the first start downloads yolo11n.pt, about 6 MB):
[yolo_detector]: loaded yolo11n.pt: 80 classes
[yolo_detector]: 3 objects: bottle 0.81, cup 0.68, bowl 0.67
Terminal 3, look at the results:
./docker/run_ros.sh ros2 run rqt_image_view rqt_image_view /detections/image
./docker/run_ros.sh ros2 topic echo /detections --field detections
Drive the robot around with teleop_twist_keyboard (tutorial 06) and watch the detections change.
/detections/image while the robot turns about 40° to the left, 40° to the right of its start, and back. The detector runs 5 times a second, so the video moves in steps. YOLO11n finds the bottle, the bowl and the cup most of the time. The banana, lying flat, is mostly missed, and once it is boxed as a frisbee (see Sim-to-real below).Bigger model, other settings
ros2 launch lime_yolo yolo.launch.py model:=yolo11s.pt confidence:=0.5 max_rate:=10.0. Larger models are
more accurate and slower.
The detector node: lime_yolo/yolo_detector.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""YOLO object detection on a ROS 2 image topic (tutorial 10).
Subscribes: /camera/camera/color/image_raw sensor_msgs/Image
Publishes: /detections vision_msgs/Detection2DArray (class name + score + box)
/detections/image sensor_msgs/Image (image with boxes drawn)
The detector uses Ultralytics YOLO (https://docs.ultralytics.com, AGPL-3.0) on the CPU. To keep the CPU load
low it only processes the newest image, at most `max_rate` times per second.
"""
import os
import time
import rclpy
from cv_bridge import CvBridge
from rclpy.node import Node
from sensor_msgs.msg import Image
from vision_msgs.msg import Detection2D, Detection2DArray, ObjectHypothesisWithPose
class YoloDetector(Node):
def __init__(self):
super().__init__("yolo_detector")
self.declare_parameter("model", "yolo11n.pt") # downloaded on first use (~6 MB)
self.declare_parameter("confidence", 0.35)
self.declare_parameter("max_rate", 5.0) # Hz
self.declare_parameter("image_topic", "/camera/camera/color/image_raw")
self.confidence = self.get_parameter("confidence").value
model_name = self.get_parameter("model").value
# Weights are cached outside the repository (they are not part of it - AGPL-3.0).
cache = os.path.expanduser("~/.cache/lime_yolo")
os.makedirs(cache, exist_ok=True)
os.chdir(cache)
from ultralytics import YOLO # imported here: it is slow to import
self.model = YOLO(model_name)
self.get_logger().info(f"loaded {model_name}: {len(self.model.names)} classes")
self.bridge = CvBridge()
self.latest = None
topic = self.get_parameter("image_topic").value
self.create_subscription(Image, topic, self.on_image, 1) # queue of 1: keep only the newest image
self.det_pub = self.create_publisher(Detection2DArray, "/detections", 10)
self.img_pub = self.create_publisher(Image, "/detections/image", 1)
# Wall-clock timer: detection speed is limited by the CPU, not by simulation time.
self.create_timer(1.0 / self.get_parameter("max_rate").value, self.detect, clock=rclpy.clock.Clock())
self.last_log = 0.0
self.get_logger().info(f"waiting for images on {topic}")
def on_image(self, msg: Image):
self.latest = msg
def detect(self):
msg, self.latest = self.latest, None
if msg is None:
return
rgb = self.bridge.imgmsg_to_cv2(msg, desired_encoding="rgb8")
result = self.model.predict(rgb[:, :, ::-1], conf=self.confidence, verbose=False)[0] # YOLO wants BGR
out = Detection2DArray(header=msg.header)
for box in result.boxes:
x1, y1, x2, y2 = (float(v) for v in box.xyxy[0])
det = Detection2D(header=msg.header)
det.bbox.center.position.x = (x1 + x2) / 2.0
det.bbox.center.position.y = (y1 + y2) / 2.0
det.bbox.size_x = x2 - x1
det.bbox.size_y = y2 - y1
hyp = ObjectHypothesisWithPose()
hyp.hypothesis.class_id = self.model.names[int(box.cls)]
hyp.hypothesis.score = float(box.conf)
det.results.append(hyp)
out.detections.append(det)
self.det_pub.publish(out)
annotated = result.plot()[:, :, ::-1] # BGR -> RGB
img = self.bridge.cv2_to_imgmsg(annotated.copy(), encoding="rgb8")
img.header = msg.header
self.img_pub.publish(img)
if time.time() - self.last_log > 2.0:
found = ", ".join(f"{d.results[0].hypothesis.class_id} {d.results[0].hypothesis.score:.2f}" for d in out.detections)
self.get_logger().info(f"{len(out.detections)} objects: {found or '-'}")
self.last_log = time.time()
def main():
rclpy.init()
node = YoloDetector()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
node.destroy_node()
rclpy.try_shutdown()
if __name__ == "__main__":
main()
Isaac Sim side: isaac/10_yolo.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""Tutorial 10 - Object detection with YOLO on the RealSense images.
source scripts/isaac_env.sh
python isaac/10_yolo.py
# ROS 2 container: the detector, then look at the result
./docker/run_ros.sh ros2 launch lime_yolo yolo.launch.py
./docker/run_ros.sh ros2 run rqt_image_view rqt_image_view /detections/image
./docker/run_ros.sh ros2 topic echo /detections
Isaac Sim does the same as in tutorial 08 (lime_room + robot + camera topics). The new part runs in ROS 2:
the lime_yolo node (ros2_ws/src/lime_yolo) reads /camera/camera/color/image_raw, runs YOLO, and publishes
/detections (vision_msgs/Detection2DArray) and /detections/image (boxes drawn on the image).
"""
import sys
from common.cli import parse_args
args = parse_args(__doc__.splitlines()[0])
from isaacsim import SimulationApp
simulation_app = SimulationApp({"headless": args.headless, "width": 1280, "height": 720})
import isaacsim.core.experimental.utils.app as app_utils
import isaacsim.core.experimental.utils.stage as stage_utils
import numpy as np
from common import graphs, lime, sensors
from common.scene import OBJECTS, build_lime_room
from isaacsim.core.simulation_manager import SimulationManager
graphs.enable_ros2_realtime(simulation_app)
stage = stage_utils.create_new_stage(template="empty")
build_lime_room(stage)
while stage_utils.is_stage_loading():
simulation_app.update()
robot_path = "/World/turtlebot3_lime"
articulation_root = lime.add_lime(robot_path)
graphs.create_clock_graph()
graphs.create_drive_graph(articulation_root)
graphs.create_odom_tf_joint_states_graph(articulation_root)
graphs.create_camera_graph(sensors.add_d435_camera(robot_path))
SimulationManager.setup_simulation(dt=1.0 / 60.0)
app_utils.play()
simulation_app.update()
print("[10] ready: start the detector: ros2 launch lime_yolo yolo.launch.py", flush=True)
EXPECTED = {coco for *_, coco in OBJECTS} # cup, banana, bowl, bottle (see common/scene.py)
if args.test or args.record:
import rclpy
from sensor_msgs.msg import Image
from vision_msgs.msg import Detection2DArray
rclpy.init()
node = rclpy.create_node("lime_tutorial10_check")
seen, best, last = {}, {"img": None, "n": -1}, {"classes": set()}
def on_detections(msg):
last["classes"] = set()
for d in msg.detections:
h = d.results[0].hypothesis
seen[h.class_id] = max(seen.get(h.class_id, 0.0), h.score)
last["classes"].add(h.class_id)
def on_image(msg): # keep the annotated image showing the most expected objects at once
n = len(EXPECTED & last["classes"])
if n >= best["n"]:
best.update(img=msg, n=n)
node.create_subscription(Detection2DArray, "/detections", on_detections, 10)
node.create_subscription(Image, "/detections/image", on_image, 1)
steps, done_at = 0, None
while simulation_app.is_running():
simulation_app.update()
steps += 1
if args.test or args.record:
for _ in range(10):
rclpy.spin_once(node, timeout_sec=0.0)
if done_at is None and len(EXPECTED & set(seen)) == len(EXPECTED):
done_at = steps
if (done_at is not None and steps - done_at > 120) or steps > 180 * 60: # all found, or 3 min
break
ok = True
if args.test or args.record:
found = EXPECTED & set(seen)
for cls in sorted(EXPECTED):
print(f"[10][check] {'ok ' if cls in seen else 'FAIL'} detected '{cls}'" + (f" (best score {seen[cls]:.2f})" if cls in seen else ""))
others = sorted(set(seen) - EXPECTED)
if others:
print(f"[10][check] other classes reported: {others}")
ok = len(found) >= 3
if args.test:
print(f"[10][test] {len(found)}/{len(EXPECTED)} objects detected: {'PASS' if ok else 'FAIL'}")
if args.record and best["img"] is not None:
import imageio.v2 as imageio
from common.paths import IMG_DIR
m = best["img"]
imageio.imwrite(IMG_DIR / f"{args.record}_detections.png", np.frombuffer(m.data, np.uint8).reshape(m.height, m.width, 3))
print(f"[10] saved {IMG_DIR / (args.record + '_detections.png')}")
node.destroy_node()
rclpy.shutdown()
app_utils.stop()
simulation_app.close(exit_code=0 if ok else 1)
sys.exit(0 if ok else 1)
Automatic check¶
python isaac/10_yolo.py --headless --test listens to /detections (Isaac Sim's own rclpy has vision_msgs) and
passes when at least 3 of the 4 placed objects are detected. Start the detector in the container while it runs
(tools/run_all_checks.sh 10 does both):
[10][check] ok detected 'banana' (best score 0.39)
[10][check] ok detected 'bottle' (best score 0.86)
[10][check] ok detected 'bowl' (best score 0.78)
[10][check] ok detected 'cup' (best score 0.77)
[10][check] other classes reported: ['frisbee']
[10][test] 4/4 objects detected: PASS
Sim-to-real: what the scores tell you
The bottle and the bowl are detected with high confidence. The banana and the cup get lower scores, and the flat red bowl is sometimes taken for a frisbee. The camera is only 5.8 cm above the floor, so it sees the objects from an unusual angle, and the COCO photos rarely show them that way. A real robot has the same problem. Simulation lets you see it, and generate training images for it, before the robot exists.