コンテンツにスキップ

10 · YOLO で物体検出

⏱ 20 分 · レベル:初級 · スクリプト:isaac/10_yolo.py · ROS:lime_yolo

目標: Lime のカメラ画像に写った日用品を、YOLO で検出します。検出器は普通の ROS 2 ノードです。画像がシミュレーターから来ていることを知りませんし、気にもしません。

シミュレーション上の RealSense の画像に対する YOLO の検出結果

/detections/image:YOLO11n が、チュートリアル 08 のカメラに写っているボウル、マグカップ、バナナ、ボトルを見つけています。

考え方

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」の略)は、リアルタイム物体検出器のファミリーです。学習済みモデルは、COCO データセットにある日用品の 80 クラスを知っています:cup, bowl, banana, bottle, chair, person, …。lime_room の物体は、これらのクラスから選びました。
  • vision_msgs/Detection2DArray は、2D の検出結果を表す ROS の標準メッセージです。物体ごとに 1 つのエントリーがあり、バウンディングボックス(中心とサイズ、単位はピクセル)と、スコア付きのクラス名を持ちます。
  • ノードは最新の画像だけを、多くても毎秒 5 回処理します。CPU でもデモには十分で、シミュレーションがノードを待つこともありません。

ライセンス

チュートリアルのコードは Apache-2.0 です。Ultralytics YOLO は AGPL-3.0 です。Ultralytics YOLO は Docker イメージにインストールされ、モデルの重みは初回使用時に(コンテナ内の ~/.cache/lime_yolo に)ダウンロードされます。どちらもこのリポジトリには含まれていません。製品に使う前に、ライセンスを確認してください。NVIDIA の Isaac ROS isaac_ros_yolov8 は、GPU (TensorRT) で高速化された上級者向けの代替手段です。

実行してみる

ターミナル 1 では、Isaac Sim を起動します(チュートリアル 08 と同じシーンです)。

source scripts/isaac_env.sh
python isaac/10_yolo.py

ターミナル 2 では、検出器を起動します(初回の起動時には、約 6 MB の yolo11n.pt をダウンロードします)。

./scripts/build_ws.sh lime_yolo        # once
./docker/run_ros.sh ros2 launch lime_yolo yolo.launch.py
[yolo_detector]: loaded yolo11n.pt: 80 classes
[yolo_detector]: 3 objects: bottle 0.81, cup 0.68, bowl 0.67

ターミナル 3 では、結果を見ます。

./docker/run_ros.sh ros2 run rqt_image_view rqt_image_view /detections/image
./docker/run_ros.sh ros2 topic echo /detections --field detections

teleop_twist_keyboard(チュートリアル 06)でロボットを走らせ、検出結果が変わる様子を見てください。

ロボットがスタート時の向きから左に約 40°、右に 40° 回り、元の向きに戻る間の /detections/image。検出器は毎秒 5 回動くので、動画はコマ送りのように動きます。YOLO11n は、ほとんどの時間、ボトル、ボウル、マグカップを見つけています。平らに置かれたバナナはほとんど見逃され、一度は frisbee として囲まれています(下の Sim-to-real を参照)。

より大きなモデル、ほかの設定

ros2 launch lime_yolo yolo.launch.py model:=yolo11s.pt confidence:=0.5 max_rate:=10.0。大きなモデルほど精度が高くなり、遅くなります。

検出器ノード: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 側: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)

自動チェック

python isaac/10_yolo.py --headless --test は /detections をサブスクライブし(Isaac Sim 自身の rclpy には vision_msgs が入っています)、配置した 4 つの物体のうち 3 つ以上が検出されれば合格です。これを実行している間に、コンテナで検出器を起動してください(tools/run_all_checks.sh 10 は両方を行います)。

[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:スコアからわかること

ボトルとボウルは、高い信頼度で検出されます。バナナとマグカップはスコアが低く、平たい赤いボウルは frisbee と判定されることがあります。カメラは床から 5.8 cm の高さしかないので、物体を見慣れない角度から見ることになります。COCO の写真に、そのような角度から写したものはめったにありません。実機にも同じ問題があります。シミュレーションなら、ロボットが存在する前にこの問題を確かめ、その対策のための学習用画像を生成することもできます。

次へ: 11 · Nav2 でナビゲーション