Link to this sectionUltralytics YOLOによるマルチオブジェクトトラッキング#
ビデオ解析におけるオブジェクトトラッキングは、フレーム内のオブジェクトの位置とクラスを識別するだけでなく、ビデオの進行に合わせて各検出オブジェクトの固有IDを維持する重要なタスクです。その応用範囲は、監視やセキュリティからリアルタイムのスポーツ解析まで無限に広がっています。
Link to this sectionなぜオブジェクトトラッキングにUltralytics YOLOを選ぶのか?#
Ultralyticsトラッカーの出力は標準的なオブジェクト検出と一貫していますが、オブジェクトIDという付加価値があります。これにより、ビデオストリーム内のオブジェクトを簡単に追跡し、後続の解析を実行できます。Ultralytics YOLOをオブジェクトトラッキングのニーズに検討すべき理由は以下の通りです。
- 効率性: 精度を損なうことなく、リアルタイムでビデオストリームを処理します。
- 柔軟性: 複数のトラッキングアルゴリズムと構成をサポートしています。
- 使いやすさ: 迅速な統合とデプロイのためのシンプルなPython APIとCLIオプションを提供します。
- カスタマイズ性: カスタムトレーニングしたYOLOモデルで簡単に使用でき、ドメイン固有のアプリケーションへの統合が可能です。
Watch: How to Run Multi-Object Tracking with Ultralytics YOLO26 | BoT-SORT & ByteTrack | VisionAI 🚀
Link to this section実際のアプリケーション#
| 交通機関 | 小売 | 水産養殖 |
|---|---|---|
| 車両トラッキング | 人物トラッキング | 魚類トラッキング |
Link to this section機能の概要#
Ultralytics YOLOは、オブジェクト検出機能を拡張し、堅牢で汎用性の高いオブジェクトトラッキングを提供します。
- リアルタイムトラッキング: 高フレームレートのビデオ内のオブジェクトをシームレスに追跡します。
- マルチトラッカーサポート: 確立されたさまざまなトラッキングアルゴリズムから選択できます。
- カスタマイズ可能なトラッカー設定: さまざまなパラメータを調整することで、特定の要件に合わせてトラッキングアルゴリズムを調整できます。
Link to this section利用可能なトラッカー#
Ultralytics YOLOは以下のトラッキングアルゴリズムをサポートしています。これらは、tracker=tracker_type.yamlのような関連するYAML構成ファイルを渡すことで有効にできます。
デフォルトのトラッカーはBoT-SORTです。
Link to this sectionトラッキング#
ビデオストリームでトラッカーを実行するには、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モデルで利用可能です。
Link to this section設定#
Link to this sectionトラッキング引数#
トラッキング構成は、conf、iou、showなどの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)Link to this sectionトラッカーの選択#
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")各パラメータの詳細な説明については、トラッカー引数セクションを参照してください。
Link to this sectionトラッカー引数#
一部のトラッキング動作は、各トラッキングアルゴリズム固有のYAML構成ファイルを編集することで微調整できます。これらのファイルは、しきい値、バッファ、マッチングロジックなどのパラメータを定義します。
次の表は、各パラメータの説明を示しています。
検出の信頼度スコアがtrack_high_threshを下回る場合、トラッカーはそのオブジェクトを更新せず、アクティブなトラックは生成されません。
| パラメータ | 有効な値または範囲 | 説明 |
|---|---|---|
tracker_type | botsort, bytetrack | トラッカーの種類を指定します。オプションはbotsortまたはbytetrackです。 |
track_high_thresh | 0.0-1.0 | トラッキング中の最初の関連付けに使用されるしきい値。検出が既存のトラックとどれだけ確実に関連付けられるかに影響します。 |
track_low_thresh | 0.0-1.0 | トラッキング中の2回目の関連付けのしきい値。最初の関連付けが失敗した場合に、より寛容な基準で使用されます。 |
new_track_thresh | 0.0-1.0 | 検出がいずれの既存のトラックとも一致しない場合に、新しいトラックを初期化するためのしきい値。新しいオブジェクトが出現したとみなされるタイミングを制御します。 |
track_buffer | >=0 | 失われたトラックが削除される前に維持されるフレーム数を示すバッファ。値が大きいほど、オクルージョンに対する許容度が高まります。 |
match_thresh | 0.0-1.0 | トラックマッチングのしきい値。値を大きくするとマッチングがより寛容になります。 |
fuse_score | True, False | マッチング前に信頼度スコアをIoU距離と融合するかどうかを決定します。関連付けを行う際に空間情報と信頼度情報のバランスをとるのに役立ちます。 |
gmc_method | orb, sift, ecc, sparseOptFlow, None | グローバルモーション補正に使用されるメソッド。カメラの動きを考慮してトラッキングを改善するのに役立ちます。 |
proximity_thresh | 0.0-1.0 | ReID(再識別)で有効な一致に必要な最小IoU。外観の手掛かりを使用する前に、空間的な近接性を確保します。 |
appearance_thresh | 0.0-1.0 | ReIDに必要な最小の外観類似度。2つの検出をリンクさせるために、視覚的にどれだけ類似している必要があるかを設定します。 |
with_reid | True, False | ReIDを使用するかどうかを示します。オクルージョンをまたいだより良いトラッキングのために外観ベースのマッチングを有効にします。BoTSORTでのみサポートされます。 |
model | auto, yolo26[nsmlx]-cls.pt | 使用するモデルを指定します。デフォルトはautoで、検出器がYOLOの場合はネイティブ機能を使用し、それ以外の場合はyolo26n-cls.ptを使用します。 |
Link to this section再識別(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のようなより高速なバックエンドにエクスポートできます。
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に使用されます。
Link to this sectionPythonの例#
Watch: How to Build Interactive Object Tracking with Ultralytics YOLO | Click to Crop & Display ⚡
Link to this section永続的なトラックのループ#
以下は、OpenCV(cv2)とYOLO26を使用してビデオフレームでオブジェクトトラッキングを実行するPythonスクリプトです。このスクリプトは、必要なパッケージ(opencv-pythonおよびultralytics)が既にインストールされていることを前提としています。persist=True引数は、現在の画像またはフレームがシーケンス内の次のものであり、前の画像のトラックを現在の画像で期待するようにトラッカーに伝えます。
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」を押すことで終了できます。
Link to this section時間の経過に伴うトラックのプロット#
連続するフレームにわたってオブジェクトトラックを可視化することで、ビデオ内で検出されたオブジェクトの移動パターンや行動に関する貴重な洞察を得ることができます。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()Link to this sectionマルチスレッドトラッキング#
マルチスレッドトラッキングは、複数のビデオストリームで同時にオブジェクトトラッキングを実行する機能を提供します。これは、複数の監視カメラからのビデオ入力など、複数のビデオ入力を扱う場合に特に有用で、同時処理により効率とパフォーマンスが大幅に向上します。
提供されたPythonスクリプトでは、Pythonのthreadingモジュールを使用して、トラッカーの複数のインスタンスを同時に実行します。各スレッドは1つのビデオファイルでトラッカーを実行する役割を担い、すべてのスレッドがバックグラウンドで同時に実行されます。
各スレッドが正しいパラメータ(ビデオファイル、使用するモデル、ファイルインデックス)を受け取るように、これらのパラメータを受け取り、メインのトラッキングループを含むrun_tracker_in_thread関数を定義します。この関数はビデオをフレームごとに読み取り、トラッカーを実行し、結果を表示します。
この例では、yolo26n.ptとyolo26n-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()この例は、より多くのスレッドを作成し、同じ方法論を適用することで、より多くのビデオファイルやモデルを処理するように簡単に拡張できます。
Link to this section新しいトラッカーをコントリビュートする#
マルチオブジェクトトラッキングに精通しており、Ultralytics YOLOを使用してトラッキングアルゴリズムの実装や適応を成功させた経験はありますか?ultralytics/cfg/trackersのTrackersセクションへのコントリビューションを募集しています!あなたの実際のアプリケーションやソリューションは、トラッキングタスクに取り組むユーザーにとって非常に価値のあるものとなるでしょう。
このセクションに貢献することで、Ultralytics YOLOフレームワーク内で利用可能なトラッキングソリューションの範囲が広がり、コミュニティにとっての機能性と利便性が向上します。
コントリビューションを開始するには、Contributing Guideを参照して、Pull Request (PR) 🛠️の提出に関する包括的な手順を確認してください。皆様からの投稿を楽しみにしています!
Ultralytics YOLOエコシステムのトラッキング機能を共に強化していきましょう 🙏!
Link to this sectionFAQ#
Link to this sectionマルチオブジェクトトラッキングとは何ですか?また、Ultralytics YOLOはどのようにそれをサポートしていますか?#
ビデオアナリティクスにおけるマルチオブジェクトトラッキングには、オブジェクトの特定と、ビデオフレーム間で検出された各オブジェクトの一意なIDの維持の両方が含まれます。Ultralytics YOLOは、オブジェクトIDとともにリアルタイムトラッキングを提供することでこれをサポートし、セキュリティ監視やスポーツアナリティクスなどのタスクを促進します。このシステムでは、YAMLファイルを介して設定可能なBoT-SORTやByteTrackといったトラッカーを使用します。
Link to this sectionUltralytics YOLOでカスタムトラッカーを設定するにはどうすればよいですか?#
既存のトラッカー設定ファイル(例:custom_tracker.yaml)をUltralyticsトラッカー設定ディレクトリからコピーし、tracker_type以外の必要なパラメータを変更することで、カスタムトラッカーを設定できます。このファイルを以下のようにトラッキングモデルで使用します。
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker="custom_tracker.yaml")Link to this section複数のビデオストリームで同時にオブジェクトトラッキングを実行するにはどうすればよいですか?#
複数のビデオストリームで同時にオブジェクトトラッキングを実行するには、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()Link to this sectionUltralytics YOLOを使用したマルチオブジェクトトラッキングにはどのような実世界のアプリケーションがありますか?#
Ultralytics YOLOを使用したマルチオブジェクトトラッキングには、以下のような多数のアプリケーションがあります。
- 交通: 交通管理および自動運転のための車両トラッキング。
- 小売: 店内分析やセキュリティのための人物トラッキング。
- 水産養殖: 水環境を監視するための魚のトラッキング。
- スポーツアナリティクス: パフォーマンス分析のための選手や用具のトラッキング。
- セキュリティシステム: 不審な活動の監視およびセキュリティアラームの作成。
これらのアプリケーションは、高フレームレートのビデオをリアルタイムかつ非常に高い精度で処理するUltralytics YOLOの能力を活用しています。
Link to this sectionUltralytics 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()このスクリプトは、時間の経過に伴うトラッキング対象の移動経路を示すトラッキングラインをプロットし、オブジェクトの行動やパターンに関する貴重な洞察を提供します。