コンテンツへスキップ

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

複数オブジェクトのトラッキング例

ビデオ解析の領域におけるオブジェクトトラッキングは、フレーム内のオブジェクトの位置とクラスを識別するだけでなく、ビデオの進行に応じて検出された各オブジェクトの一意のIDを維持する重要なタスクです。監視やセキュリティからリアルタイムのスポーツ分析まで、アプリケーションは無限です。

物体追跡にUltralytics YOLO を選ぶ理由は?

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

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



見るんだ: Ultralytics YOLOv8 による物体検出と追跡 .

実世界での応用

交通 小売 水産養殖
車両追跡 ピープル・トラッキング 魚の追跡
車両追跡 ピープル・トラッキング 魚の追跡

特徴一覧

Ultralytics YOLO オブジェクト検出機能を拡張し、ロバストで多目的なオブジェクトトラッキングを提供します:

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

利用可能なトラッカー

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

  • ボット・ソート - 用途 botsort.yaml をクリックして、このトラッカーを有効にしてください。
  • バイトトラック - 用途 bytetrack.yaml をクリックして、このトラッカーを有効にしてください。

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

トラッキング

トラッカーしきい値情報

オブジェクトの信頼度スコアが低い場合、つまり、以下のようになる。 track_high_threshその場合、正常に返され更新されたトラックはない。

ビデオストリームでトラッカーを実行するには、YOLOv8n 、YOLOv8n-seg、YOLOv8n-pose のような学習済みの検出、セグメント、ポーズモデルを使用する。

from ultralytics import YOLO

# Load an official or custom model
model = YOLO('yolov8n.pt')  # Load an official Detect model
model = YOLO('yolov8n-seg.pt')  # Load an official Segment model
model = YOLO('yolov8n-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(source="https://youtu.be/LNwODJXcvt4", show=True)  # Tracking with default tracker
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")  # Tracking with ByteTrack tracker
# Perform tracking with various models using the command line interface
yolo track model=yolov8n.pt source="https://youtu.be/LNwODJXcvt4"  # Official Detect model
yolo track model=yolov8n-seg.pt source="https://youtu.be/LNwODJXcvt4"  # Official Segment model
yolo track model=yolov8n-pose.pt source="https://youtu.be/LNwODJXcvt4"  # Official Pose model
yolo track model=path/to/best.pt source="https://youtu.be/LNwODJXcvt4"  # Custom trained model

# Track using ByteTrack tracker
yolo track model=path/to/best.pt tracker="bytetrack.yaml"

上記の使用方法からわかるように、トラッキングはビデオやストリーミングソース上で実行される全てのDetect、Segment、Poseモデルで利用可能です。

構成

トラッカーしきい値情報

オブジェクトの信頼度スコアが低い場合、つまり、以下のようになる。 track_high_threshその場合、正常に返され更新されたトラックはない。

引数の追跡

トラッキング設定は、次のようなプロパティを予測モードと共有している。 conf, iouそして show.詳細な設定については 予測する のモデルページ。

from ultralytics import YOLO

# Configure the tracking parameters and run the tracker
model = YOLO('yolov8n.pt')
results = model.track(source="https://youtu.be/LNwODJXcvt4", conf=0.3, iou=0.5, show=True)
# Configure tracking parameters and run the tracker using the command line interface
yolo track model=yolov8n.pt source="https://youtu.be/LNwODJXcvt4" conf=0.3, iou=0.5 show

トラッカーの選択

Ultralytics また、修正したトラッカー設定ファイルを使うこともできます。これを行うには、単純にトラッカー設定ファイルのコピー(例えば、 custom_tracker.yamlより)。 ultralytics/トラッカーズ を除く)を変更する。 tracker_type)をニーズに合わせて選択することができる。

from ultralytics import YOLO

# Load the model and run the tracker with a custom configuration file
model = YOLO('yolov8n.pt')
results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker='custom_tracker.yaml')
# Load the model and run the tracker with a custom configuration file using the command line interface
yolo track model=yolov8n.pt source="https://youtu.be/LNwODJXcvt4" tracker='custom_tracker.yaml'

トラッキング引数の包括的なリストについては、ultralytics/cfg/trackersページを参照して下さい。

Python 例

パーシステング・トラック・ループ

以下はOpenCVを使ったPython スクリプトである。cv2)とYOLOv8 、ビデオフレームに対してオブジェクトトラッキングを実行します。このスクリプトは、必要なパッケージ(opencv-python そして ultralytics).その persist=True 引数は、現在の画像またはフレームがシーケンスの次であり、現在の画像に前の画像からのトラックを期待することをトラッカーに伝えます。

トラッキング付きストリーミング・フォーループ

import cv2
from ultralytics import YOLO

# Load the YOLOv8 model
model = YOLO('yolov8n.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 YOLOv8 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("YOLOv8 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 YOLOv8 を使えば、これらの軌跡をシームレスかつ効率的にプロットすることができます。

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

複数のビデオフレームにトラックをプロットする

from collections import defaultdict

import cv2
import numpy as np

from ultralytics import YOLO

# Load the YOLOv8 model
model = YOLO('yolov8n.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 YOLOv8 tracking on the frame, persisting tracks between frames
        results = model.track(frame, persist=True)

        # Get the boxes and track IDs
        boxes = results[0].boxes.xywh.cpu()
        track_ids = results[0].boxes.id.int().cpu().tolist()

        # Visualize the results on the frame
        annotated_frame = results[0].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 90 tracks for 90 frames
                track.pop(0)

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

        # Display the annotated frame
        cv2.imshow("YOLOv8 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()

マルチスレッド追跡

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

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

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

この例では2つの異なるモデルを使用している: yolov8n.pt そして yolov8n-seg.ptそれぞれ異なるビデオファイルのオブジェクトを追跡する。ビデオファイルは video_file1 そして video_file2.

について daemon=True パラメータの threading.Thread つまり、メイン・プログラムが終了すると同時に、これらのスレッドはクローズされる。次に、スレッドを start() そして join() を使うことで、両方のトラッカースレッドが終了するまでメインスレッドを待たせることができる。

最後に、すべてのスレッドがタスクを完了したら、結果を表示するウィンドウは cv2.destroyAllWindows().

トラッキング付きストリーミング・フォーループ

import threading
import cv2
from ultralytics import YOLO


def run_tracker_in_thread(filename, model, file_index):
    """
    Runs a video file or webcam stream concurrently with the YOLOv8 model using threading.

    This function captures video frames from a given file or camera source and utilizes the YOLOv8 model for object
    tracking. The function runs in its own thread for concurrent processing.

    Args:
        filename (str): The path to the video file or the identifier for the webcam/external camera source.
        model (obj): The YOLOv8 model object.
        file_index (int): An index to uniquely identify the file being processed, used for display purposes.

    Note:
        Press 'q' to quit the video display window.
    """
    video = cv2.VideoCapture(filename)  # Read the video file

    while True:
        ret, frame = video.read()  # Read the video frames

        # Exit the loop if no more frames in either video
        if not ret:
            break

        # Track objects in frames if available
        results = model.track(frame, persist=True)
        res_plotted = results[0].plot()
        cv2.imshow(f"Tracking_Stream_{file_index}", res_plotted)

        key = cv2.waitKey(1)
        if key == ord('q'):
            break

    # Release video sources
    video.release()


# Load the models
model1 = YOLO('yolov8n.pt')
model2 = YOLO('yolov8n-seg.pt')

# Define the video files for the trackers
video_file1 = "path/to/video1.mp4"  # Path to video file, 0 for webcam
video_file2 = 0  # Path to video file, 0 for webcam, 1 for external camera

# Create the tracker threads
tracker_thread1 = threading.Thread(target=run_tracker_in_thread, args=(video_file1, model1, 1), daemon=True)
tracker_thread2 = threading.Thread(target=run_tracker_in_thread, args=(video_file2, model2, 2), daemon=True)

# Start the tracker threads
tracker_thread1.start()
tracker_thread2.start()

# Wait for the tracker threads to finish
tracker_thread1.join()
tracker_thread2.join()

# Clean up and close windows
cv2.destroyAllWindows()

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

新しいトラッカーを投稿する

あなたは多オブジェクトトラッキングに精通し、Ultralytics YOLO 、トラッキングアルゴリズムの実装や適応に成功したことがありますか?ultralytics/cfg/trackers の Trackers セクションへの投稿をお待ちしています!あなたの実際のアプリケーションやソリューションは、トラッキングタスクに取り組むユーザーにとって貴重なものとなるでしょう。

このセクションに貢献することで、Ultralytics YOLO フレームワークで利用可能なトラッキング・ソリューションの範囲を拡大し、コミュニティのために機能とユーティリティの新たなレイヤーを追加するのに役立ちます。

あなたの貢献を開始するには、プルリクエスト (PR) 🛠️ を提出するための包括的な手順については、貢献ガイドを参照してください。私たちは、あなたが何をもたらしてくれるかを楽しみにしています!

一緒に、Ultralytics YOLO エコシステム🙏のトラッキング機能を強化しましょう!



作成日:2023-11-12 更新日:2024-04-26
作成者:glenn-jocher(11)

コメント