Ultralytics YOLOによるマルチオブジェクトトラッキング

YOLO multi-object tracking with trajectory paths

ビデオ解析におけるオブジェクトトラッキングは、フレーム内のオブジェクトの位置やクラスを識別するだけでなく、ビデオの進行に合わせて検出された各オブジェクトの一意なIDを保持する重要なタスクです。その応用範囲は、監視やセキュリティからリアルタイムのスポーツ解析まで無限に広がっています。

なぜオブジェクトトラッキングにUltralytics YOLOを選ぶのか?

Ultralyticsトラッカーの出力は標準的なオブジェクト検出と一貫していますが、オブジェクトIDという付加価値があります。これにより、ビデオストリーム内のオブジェクトを簡単に追跡し、その後の解析を実行できます。Ultralytics YOLOをオブジェクトトラッキングのニーズに利用すべき理由は以下の通りです。

  • 効率性: 精度を犠牲にすることなく、リアルタイムでビデオストリームを処理します。
  • 柔軟性: 複数のトラッキングアルゴリズムと構成をサポートしています。
  • 使いやすさ: 迅速な統合とデプロイのためのシンプルなPython APIとCLIオプションを提供します。
  • カスタマイズ性: カスタムトレーニングしたYOLOモデルを簡単に使用でき、ドメイン固有のアプリケーションへの統合が可能です。


Watch: How to Run Multi-Object Tracking with Ultralytics YOLO26 | BoT-SORT & ByteTrack | VisionAI 🚀

実世界のアプリケーション

交通機関小売水産養殖
車両トラッキング人物トラッキング魚トラッキング
車両トラッキング人物トラッキング魚トラッキング

機能の概要

Ultralytics YOLOは、オブジェクト検出機能を拡張し、堅牢で汎用性の高いオブジェクトトラッキングを提供します。

  • リアルタイムトラッキング: 高フレームレートのビデオ内でシームレスにオブジェクトを追跡します。
  • 複数のトラッカーサポート: さまざまな確立されたトラッキングアルゴリズムから選択できます。
  • カスタマイズ可能なトラッカー設定: さまざまなパラメータを調整して、特定の要件に合わせてトラッキングアルゴリズムを調整します。

利用可能なトラッカー

Ultralytics YOLOは以下のトラッキングアルゴリズムをサポートしています。これらは、tracker=tracker_type.yamlのような関連するYAML設定ファイルを渡すことで有効にできます。

  • BoT-SORT - このトラッカーを有効にするには botsort.yaml を使用します。
  • ByteTrack - このトラッカーを有効にするには bytetrack.yaml を使用します。

デフォルトのトラッカーはBoT-SORTです。

トラッキング

ビデオストリームでトラッカーを実行するには、YOLO26n、YOLO26n-seg、YOLO26n-poseのような学習済みのDetect、Segment、またはPoseモデルを使用してください。カスタムモデルはローカルで、またはUltralytics Platformを通じてクラウドGPU上で学習できます。

from ultralytics import YOLO

# Load an official or custom model
model = YOLO("yolo26n.pt")  # Load an official Detect model
model = YOLO("yolo26n-seg.pt")  # Load an official Segment model
model = YOLO("yolo26n-pose.pt")  # Load an official Pose model
model = YOLO("path/to/best.pt")  # Load a custom-trained model

# Perform tracking with the model
results = model.track("https://youtu.be/LNwODJXcvt4", show=True)  # Tracking with default tracker
results = model.track("https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")  # with ByteTrack

上記の使い方の通り、トラッキングはビデオやストリーミングソースで実行されるすべてのDetect、Segment、およびPoseモデルで利用可能です。

設定

トラッキングの引数

トラッキングの設定は、confioushowなどのPredictモードとプロパティを共有します。さらなる設定については、Predictモデルページを参照してください。

from ultralytics import YOLO

# Configure the tracking parameters and run the tracker
model = YOLO("yolo26n.pt")
results = model.track(source="https://youtu.be/LNwODJXcvt4", conf=0.1, iou=0.7, show=True)

トラッカーの選択

Ultralytics also allows you to use a modified tracker configuration file. To do this, simply make a copy of a tracker config file (for example, custom_tracker.yaml) from ultralytics/cfg/trackers and modify any configurations (except the tracker_type) as per your needs.

from ultralytics import YOLO

# Load the model and run the tracker with a custom configuration file
model = YOLO("yolo26n.pt")
results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker="custom_tracker.yaml")

各パラメータの詳細については、トラッカーの引数セクションを参照してください。

トラッカーの引数

一部のトラッキング動作は、各トラッキングアルゴリズム固有のYAML設定ファイルを編集することで微調整できます。これらのファイルは、しきい値、バッファ、マッチングロジックなどのパラメータを定義します。

次の表は各パラメータの説明を提供します。

トラッカーしきい値情報

検出の信頼スコアが track_high_thresh を下回る場合、トラッカーはそのオブジェクトを更新せず、アクティブなトラックは発生しません。

パラメータ有効な値または範囲説明
tracker_typebotsort, bytetrackトラッカーの種類を指定します。オプションは botsort または bytetrack です。
track_high_thresh0.0-1.0トラッキング中の最初の関連付けに使用されるしきい値。検出が既存のトラックとどれだけ確実に一致するかに関係します。
track_low_thresh0.0-1.0トラッキング中の2回目の関連付け用のしきい値。最初の一致が失敗したときに、より緩やかな基準で使用されます。
new_track_thresh0.0-1.0検出が既存のトラックと一致しない場合に新しいトラックを初期化するためのしきい値。新しいオブジェクトが出現したと見なされるタイミングを制御します。
track_buffer>=0消失したトラックが削除される前に存続させるフレーム数を示すバッファ。値が高いほど、オクルージョンに対する許容度が高まります。
match_thresh0.0-1.0トラック一致用のしきい値。値を大きくすると一致がより寛容になります。
fuse_scoreTrue, False一致させる前に信頼スコアとIoU距離を融合するかどうかを決定します。関連付けを行う際に空間情報と信頼情報のバランスを取るのに役立ちます。
gmc_methodorb, sift, ecc, sparseOptFlow, Noneグローバルモーション補正に使用される手法。カメラの動きを考慮してトラッキングを改善します。
proximity_thresh0.0-1.0ReID(再識別)で有効な一致に必要な最小IoU。外観の手がかりを使用する前に空間的な近接性を確保します。
appearance_thresh0.0-1.0ReIDに必要な最小の外観類似度。リンクされるために2つの検出が視覚的にどれだけ似ている必要があるかを設定します。
with_reidTrue, FalseReIDを使用するかどうかを示します。オクルージョンをまたいだより良いトラッキングのために、外観ベースのマッチングを有効にします。BoTSORTでのみサポートされます。
modelauto, yolo26[nsmlx]-cls.pt使用するモデルを指定します。デフォルトは auto で、検出器がYOLOの場合はネイティブ機能を使用し、それ以外の場合は yolo26n-cls.pt を使用します。

再識別(ReID)の有効化

By default, ReID is turned off to minimize performance overhead. Enabling it is simple—just set with_reid: True in the tracker configuration. You can also customize the model used for ReID, allowing you to trade off accuracy and speed depending on your use case:

  • ネイティブ機能 (model: auto): これはReIDのためにYOLO検出器から直接特徴を利用し、オーバーヘッドを最小限に抑えます。パフォーマンスに大きな影響を与えずに一定レベルのReIDが必要な場合に最適です。検出器がネイティブ機能をサポートしていない場合、自動的に yolo26n-cls.pt の使用にフォールバックします。
  • YOLO分類モデル: ReID特徴抽出のために、分類モデル(例:yolo26n-cls.pt)を明示的に設定できます。これにより、より識別力の高い埋め込みを提供できますが、追加の推論ステップによりレイテンシが増加します。

パフォーマンスを向上させるために、特にReID用に別の分類モデルを使用する場合は、TensorRTなどのより高速なバックエンドにエクスポートできます。

ReIDモデルをTensorRTにエクスポートする
from torch import nn

from ultralytics import YOLO

# Load the classification model
model = YOLO("yolo26n-cls.pt")

# Add average pooling layer
head = model.model.model[-1]
pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(start_dim=1))
pool.f, pool.i = head.f, head.i
model.model.model[-1] = pool

# Export to TensorRT
model.export(format="engine", half=True, dynamic=True, batch=32)

エクスポートが完了したら、トラッカー設定でTensorRTモデルのパスを指定すると、トラッキング中のReIDに使用されます。

Pythonの例



Watch: How to Build Interactive Object Tracking with Ultralytics YOLO | Click to Crop & Display ⚡

トラックの永続化ループ

以下は、OpenCV (cv2) とYOLO26を使用してビデオフレームでオブジェクトトラッキングを実行するPythonスクリプトです。このスクリプトは、必要なパッケージ(opencv-pythonultralytics)が既にインストールされていることを前提としています。persist=True 引数は、現在の画像またはフレームがシーケンス内の次の画像であり、前の画像からのトラックを現在の画像でも期待するようにトラッカーに伝えます。

トラッキングを含むストリーミングのforループ
import cv2

from ultralytics import YOLO

# Load the YOLO26 model
model = YOLO("yolo26n.pt")

# Open the video file
video_path = "path/to/video.mp4"
cap = cv2.VideoCapture(video_path)

# Loop through the video frames
while cap.isOpened():
    # Read a frame from the video
    success, frame = cap.read()

    if success:
        # Run YOLO26 tracking on the frame, persisting tracks between frames
        results = model.track(frame, persist=True)

        # Visualize the results on the frame
        annotated_frame = results[0].plot()

        # Display the annotated frame
        cv2.imshow("YOLO26 Tracking", annotated_frame)

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # Break the loop if the end of the video is reached
        break

# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()

model(frame) から model.track(frame) への変更に注意してください。これにより、単純な検出ではなくオブジェクトトラッキングが有効になります。この修正されたスクリプトは、ビデオの各フレームでトラッカーを実行し、結果を可視化してウィンドウに表示します。ループは 'q' を押すことで終了できます。

時間の経過に伴うトラックのプロット

連続したフレームにわたってオブジェクトトラックを可視化することで、ビデオ内で検出されたオブジェクトの移動パターンや挙動に関する貴重な洞察が得られます。Ultralytics YOLO26を使用すると、これらのトラックをプロットすることはシームレスで効率的なプロセスになります。

次の例では、YOLO26のトラッキング機能を利用して、複数のビデオフレームにわたって検出されたオブジェクトの動きをプロットする方法を説明します。このスクリプトは、ビデオファイルを開き、フレームごとに読み込み、YOLOモデルを使用してさまざまなオブジェクトを識別・追跡します。検出されたバウンディングボックスの中心点を保持し、それらを結ぶことで、追跡されたオブジェクトがたどった経路を表す線を描くことができます。

複数のビデオフレームにわたってトラックをプロットする
from collections import defaultdict

import cv2
import numpy as np

from ultralytics import YOLO

# Load the YOLO26 model
model = YOLO("yolo26n.pt")

# Open the video file
video_path = "path/to/video.mp4"
cap = cv2.VideoCapture(video_path)

# Store the track history
track_history = defaultdict(lambda: [])

# Loop through the video frames
while cap.isOpened():
    # Read a frame from the video
    success, frame = cap.read()

    if success:
        # Run YOLO26 tracking on the frame, persisting tracks between frames
        result = model.track(frame, persist=True)[0]

        # Get the boxes and track IDs
        if result.boxes and result.boxes.is_track:
            boxes = result.boxes.xywh.cpu()
            track_ids = result.boxes.id.int().cpu().tolist()

            # Visualize the result on the frame
            frame = result.plot()

            # Plot the tracks
            for box, track_id in zip(boxes, track_ids):
                x, y, w, h = box
                track = track_history[track_id]
                track.append((float(x), float(y)))  # x, y center point
                if len(track) > 30:  # retain 30 tracks for 30 frames
                    track.pop(0)

                # Draw the tracking lines
                points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
                cv2.polylines(frame, [points], isClosed=False, color=(230, 230, 230), thickness=10)

        # Display the annotated frame
        cv2.imshow("YOLO26 Tracking", frame)

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # Break the loop if the end of the video is reached
        break

# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()

マルチスレッドトラッキング

マルチスレッドトラッキングは、複数のビデオストリームで同時にオブジェクトトラッキングを実行する機能を提供します。これは、複数の監視カメラからの入力など、複数のビデオ入力を処理する場合に特に有用で、同時処理により効率とパフォーマンスが大幅に向上します。

提供されたPythonスクリプトでは、Pythonの threading モジュールを使用して、複数のトラッカーインスタンスを同時に実行します。各スレッドは1つのビデオファイルでトラッカーを実行する役割を担い、すべてのスレッドがバックグラウンドで同時に実行されます。

各スレッドが正しいパラメータ(ビデオファイル、使用するモデル、ファイルインデックス)を確実に受け取るようにするために、これらのパラメータを受け取り、メインのトラッキングループを含む run_tracker_in_thread 関数を定義します。この関数はビデオをフレームごとに読み込み、トラッカーを実行し、結果を表示します。

この例では yolo26n.ptyolo26n-seg.pt の2つの異なるモデルが使用され、それぞれが異なるビデオファイル内のオブジェクトを追跡します。ビデオファイルは SOURCES で指定されます。

The daemon=True parameter in threading.Thread means that these threads will be closed as soon as the main program finishes. We then start the threads with start() and use join() to make the main thread wait until both tracker threads have finished.

最後に、すべてのスレッドがタスクを完了した後、cv2.destroyAllWindows() を使用して結果を表示しているウィンドウを閉じます。

マルチスレッドトラッキングの実装
import threading

import cv2

from ultralytics import YOLO

# Define model names and video sources
MODEL_NAMES = ["yolo26n.pt", "yolo26n-seg.pt"]
SOURCES = ["path/to/video.mp4", "0"]  # local video, 0 for webcam

def run_tracker_in_thread(model_name, filename):
    """Run YOLO tracker in its own thread for concurrent processing.

    Args:
        model_name (str): The YOLO26 model object.
        filename (str): The path to the video file or the identifier for the webcam/external camera source.
    """
    model = YOLO(model_name)
    results = model.track(filename, save=True, stream=True)
    for r in results:
        pass

# Create and start tracker threads using a for loop
tracker_threads = []
for video_file, model_name in zip(SOURCES, MODEL_NAMES):
    thread = threading.Thread(target=run_tracker_in_thread, args=(model_name, video_file), daemon=True)
    tracker_threads.append(thread)
    thread.start()

# Wait for all tracker threads to finish
for thread in tracker_threads:
    thread.join()

# Clean up and close windows
cv2.destroyAllWindows()

この例は、より多くのスレッドを作成し、同じ方法論を適用することで、より多くのビデオファイルやモデルを処理するように簡単に拡張できます。

新しいトラッカーの貢献

マルチオブジェクトトラッキングに精通しており、Ultralytics YOLOを使用したトラッキングアルゴリズムの実装や適合に成功した経験はありますか?ultralytics/cfg/trackersにあるTrackersセクションへの貢献を募集しています!あなたの実際のアプリケーションやソリューションは、トラッキングタスクに取り組むユーザーにとって非常に価値のあるものとなるでしょう。

このセクションに貢献することで、Ultralytics YOLOフレームワーク内で利用可能なトラッキングソリューションの範囲が拡大され、コミュニティにとってさらなる機能性と有用性がもたらされます。

貢献を開始するには、Pull Request (PR) 🛠️の提出に関する包括的な手順が記載されたContributing Guideをご参照ください。皆さまからのご提案を楽しみにしています!

皆で協力して、Ultralytics YOLOエコシステムのトラッキング機能を強化しましょう 🙏!

FAQ

マルチオブジェクトトラッキングとは何であり、Ultralytics YOLOはどのようにそれをサポートしていますか?

ビデオ解析におけるマルチオブジェクトトラッキングには、オブジェクトの識別と、ビデオフレーム全体で検出された各オブジェクトの一意のIDを維持することの両方が含まれます。Ultralytics YOLOは、オブジェクトIDとともにリアルタイムトラッキングを提供することでこれをサポートしており、セキュリティ監視やスポーツ解析などのタスクを容易にします。このシステムはBoT-SORTByteTrackのようなトラッカーを使用しており、YAMLファイルで設定可能です。

Ultralytics YOLO用にカスタムトラッカーを設定するにはどうすればよいですか?

You can configure a custom tracker by copying an existing tracker configuration file (e.g., custom_tracker.yaml) from the Ultralytics tracker configuration directory and modifying parameters as needed, except for the tracker_type. Use this file in your tracking model like so:

from ultralytics import YOLO

model = YOLO("yolo26n.pt")
results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker="custom_tracker.yaml")

複数のビデオストリームで同時にオブジェクトトラッキングを実行するにはどうすればよいですか?

複数のビデオストリームで同時にオブジェクトトラッキングを実行するには、Pythonのthreadingモジュールを使用します。各スレッドが個別のビデオストリームを処理します。設定方法の例を以下に示します。

マルチスレッドトラッキング
import threading

import cv2

from ultralytics import YOLO

# Define model names and video sources
MODEL_NAMES = ["yolo26n.pt", "yolo26n-seg.pt"]
SOURCES = ["path/to/video.mp4", "0"]  # local video, 0 for webcam

def run_tracker_in_thread(model_name, filename):
    """Run YOLO tracker in its own thread for concurrent processing.

    Args:
        model_name (str): The YOLO26 model object.
        filename (str): The path to the video file or the identifier for the webcam/external camera source.
    """
    model = YOLO(model_name)
    results = model.track(filename, save=True, stream=True)
    for r in results:
        pass

# Create and start tracker threads using a for loop
tracker_threads = []
for video_file, model_name in zip(SOURCES, MODEL_NAMES):
    thread = threading.Thread(target=run_tracker_in_thread, args=(model_name, video_file), daemon=True)
    tracker_threads.append(thread)
    thread.start()

# Wait for all tracker threads to finish
for thread in tracker_threads:
    thread.join()

# Clean up and close windows
cv2.destroyAllWindows()

Ultralytics YOLOによるマルチオブジェクトトラッキングにはどのような実世界のアプリケーションがありますか?

Ultralytics YOLOによるマルチオブジェクトトラッキングには、以下のような多数のアプリケーションがあります。

  • 交通機関: 交通管理および自動運転のための車両トラッキング。
  • 小売: 店舗内解析およびセキュリティのための人流トラッキング。
  • 水産養殖: 水環境モニタリングのための魚類のトラッキング。
  • スポーツ解析: パフォーマンス解析のための選手および機材のトラッキング。
  • セキュリティシステム: 不審な行動の監視およびセキュリティアラームの作成。

これらのアプリケーションは、高フレームレートのビデオをリアルタイムかつ非常に高い精度で処理できるUltralytics YOLOの能力によって恩恵を受けています。

Ultralytics YOLOで複数のビデオフレームにわたってオブジェクトの軌跡を可視化するにはどうすればよいですか?

複数のビデオフレームにわたってオブジェクトの軌跡を可視化するには、YOLOモデルのトラッキング機能とOpenCVを使用して、検出されたオブジェクトの経路を描画します。これを示すスクリプトの例を以下に示します。

複数のビデオフレームにわたってトラックをプロットする
from collections import defaultdict

import cv2
import numpy as np

from ultralytics import YOLO

model = YOLO("yolo26n.pt")
video_path = "path/to/video.mp4"
cap = cv2.VideoCapture(video_path)
track_history = defaultdict(lambda: [])

while cap.isOpened():
    success, frame = cap.read()
    if success:
        results = model.track(frame, persist=True)
        boxes = results[0].boxes.xywh.cpu()
        track_ids = results[0].boxes.id.int().cpu().tolist()
        annotated_frame = results[0].plot()
        for box, track_id in zip(boxes, track_ids):
            x, y, w, h = box
            track = track_history[track_id]
            track.append((float(x), float(y)))
            if len(track) > 30:
                track.pop(0)
            points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
            cv2.polylines(annotated_frame, [points], isClosed=False, color=(230, 230, 230), thickness=10)
        cv2.imshow("YOLO26 Tracking", annotated_frame)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()

このスクリプトは、時間の経過に伴うトラッキング対象オブジェクトの移動経路を示すトラッキングラインをプロットし、オブジェクトの行動やパターンに関する貴重な洞察を提供します。

コメント