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 모델에 대해 사용 가능합니다.

구성(Configuration)

추적 인수

추적 구성은 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)

추적기 선택

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추적 중 두 번째 연관을 위한 임계값입니다. 첫 번째 연관이 실패할 때 더 관대한 기준으로 사용됩니다.
new_track_thresh0.0-1.0감지가 기존 트랙과 매칭되지 않는 경우 새 트랙을 초기화하기 위한 임계값입니다. 새 객체가 나타나는 것으로 간주되는 시점을 제어합니다.
track_buffer>=0손실된 트랙이 제거되기 전에 유지되어야 할 프레임 수를 나타내는 데 사용되는 버퍼입니다. 값이 높을수록 가려짐(occlusion)에 대한 허용치가 커집니다.
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에 필요한 최소 외형 유사도입니다. 연결되기 위해 두 감지가 시각적으로 얼마나 유사해야 하는지 설정합니다.
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-loop
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 모듈을 사용하여 여러 추적기 인스턴스를 동시에 실행합니다. 각 스레드는 하나의 비디오 파일에서 추적기를 실행하는 역할을 하며, 모든 스레드는 백그라운드에서 동시에 실행됩니다.

각 스레드가 올바른 매개변수(비디오 파일, 사용할 모델, 파일 인덱스)를 수신하도록 하기 위해 이러한 매개변수를 허용하고 메인 추적 루프를 포함하는 run_tracker_in_thread 함수를 정의합니다. 이 함수는 비디오를 프레임별로 읽고, 추적기를 실행하며, 결과를 표시합니다.

이 예제에서는 두 가지 모델(yolo26n.ptyolo26n-seg.pt)이 사용되며, 각각 다른 비디오 파일에서 객체를 추적합니다. 비디오 파일은 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

다중 객체 추적(Multi-Object Tracking)이란 무엇이며 Ultralytics YOLO는 이를 어떻게 지원하나요?

비디오 분석에서의 다중 객체 추적은 비디오 프레임 전체에서 객체를 식별하고 각 감지된 객체에 고유 ID를 유지하는 것을 포함합니다. Ultralytics YOLO는 객체 ID와 함께 실시간 추적을 제공하여 보안 감시 및 스포츠 분석과 같은 작업을 원활하게 지원합니다. 이 시스템은 BoT-SORTByteTrack과 같은 추적기를 사용하며, 이는 YAML 파일을 통해 구성할 수 있습니다.

Ultralytics 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")

여러 비디오 스트림에서 동시에 객체 추적을 실행하려면 어떻게 해야 하나요?

여러 비디오 스트림에서 동시에 객체 추적을 실행하려면 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()

이 스크립트는 시간에 따른 추적 객체의 이동 경로를 보여주는 추적 선을 그려, 객체의 행동과 패턴에 대한 유용한 통찰력을 제공합니다.

댓글