Skip to content

다중 객체 추적 Ultralytics YOLO

다중 객체 추적 예시

비디오 분석 영역에서 객체 추적은 프레임 내 객체의 위치와 클래스를 식별할 뿐만 아니라 비디오가 진행됨에 따라 감지된 각 객체에 대한 고유 ID를 유지하는 중요한 작업입니다. 감시 및 보안부터 실시간 스포츠 분석에 이르기까지 그 활용 분야는 무궁무진합니다.

객체 추적에 Ultralytics YOLO 을 선택하는 이유는 무엇인가요?

Ultralytics 트래커의 출력은 표준 객체 감지와 일치하지만 객체 ID라는 부가 가치가 있습니다. 이를 통해 동영상 스트림에서 객체를 쉽게 추적하고 후속 분석을 수행할 수 있습니다. 객체 추적에 Ultralytics YOLO 사용을 고려해야 하는 이유는 다음과 같습니다:

  • 효율성: 정확도 저하 없이 실시간으로 비디오 스트림을 처리합니다.
  • 유연성: 다양한 추적 알고리즘과 구성을 지원합니다.
  • 사용 편의성: 간단한 Python API 및 CLI 옵션으로 빠른 통합 및 배포가 가능합니다.
  • 사용자 지정 기능: 사용자 정의 훈련된 YOLO 모델을 사용하여 도메인별 애플리케이션에 쉽게 통합할 수 있습니다.



Watch: 물체 감지 및 추적 Ultralytics YOLO .

실제 애플리케이션

교통편 리테일 양식업
차량 추적 사람 추적 물고기 추적
차량 추적 사람 추적 물고기 추적

기능 살펴보기

Ultralytics YOLO 는 물체 감지 기능을 확장하여 강력하고 다양한 물체 추적을 제공합니다:

  • 실시간 추적: 고프레임률 동영상에서 오브젝트를 원활하게 추적합니다.
  • 여러 트래커 지원: 이미 확립된 다양한 추적 알고리즘 중에서 선택하세요.
  • 사용자 지정 가능한 트래커 구성: 다양한 매개변수를 조정하여 특정 요구사항을 충족하도록 추적 알고리즘을 맞춤 설정할 수 있습니다.

사용 가능한 트래커

Ultralytics YOLO 는 다음과 같은 추적 알고리즘을 지원합니다. 다음과 같은 관련 YAML 구성 파일을 전달하여 활성화할 수 있습니다. tracker=tracker_type.yaml:

  • BoT-SORT - 사용 botsort.yaml 를 클릭하여 이 트래커를 활성화합니다.
  • ByteTrack - 사용 bytetrack.yaml 를 클릭하여 이 트래커를 활성화합니다.

기본 트래커는 BoT-SORT입니다.

추적

트래커 임계값 정보

객체 신뢰도 점수가 낮을 경우(즉, 다음보다 낮은 경우) track_high_thresh를 누르면 성공적으로 반환 및 업데이트된 트랙이 없습니다.

동영상 스트림에서 트래커를 실행하려면, 훈련된 감지, 세그먼트 또는 포즈 모델(예: YOLO11n, YOLO11n-seg, YOLO11n-pose)을 사용하세요.

from ultralytics import YOLO

# Load an official or custom model
model = YOLO("yolo11n.pt")  # Load an official Detect model
model = YOLO("yolo11n-seg.pt")  # Load an official Segment model
model = YOLO("yolo11n-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
# Perform tracking with various models using the command line interface
yolo track model=yolo11n.pt source="https://youtu.be/LNwODJXcvt4"      # Official Detect model
yolo track model=yolo11n-seg.pt source="https://youtu.be/LNwODJXcvt4"  # Official Segment model
yolo track model=yolo11n-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"

위의 사용 예에서 볼 수 있듯이 동영상 또는 스트리밍 소스에서 실행되는 모든 감지, 세그먼트 및 포즈 모델에서 추적을 사용할 수 있습니다.

구성

추적 인수

추적 구성은 다음과 같이 예측 모드와 속성을 공유합니다. conf, ioushow. 추가 구성에 대해서는 예측 모델 페이지로 이동합니다.

from ultralytics import YOLO

# Configure the tracking parameters and run the tracker
model = YOLO("yolo11n.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=yolo11n.pt source="https://youtu.be/LNwODJXcvt4" conf=0.3, iou=0.5 show

트래커 선택

Ultralytics 를 사용하면 수정된 트래커 구성 파일을 사용할 수도 있습니다. 이렇게 하려면 트래커 구성 파일의 복사본을 만들기만 하면 됩니다(예 custom_tracker.yaml)에서 ultralytics/cfg/trackers 를 클릭하고 모든 구성을 수정합니다( tracker_type) 필요에 따라 조정할 수 있습니다.

from ultralytics import YOLO

# Load the model and run the tracker with a custom configuration file
model = YOLO("yolo11n.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=yolo11n.pt source="https://youtu.be/LNwODJXcvt4" tracker='custom_tracker.yaml'

각 파라미터에 대한 자세한 설명은 트래커 인수 섹션을 참조하세요.

트래커 인수

일부 추적 동작은 각 추적 알고리즘과 관련된 YAML 구성 파일을 편집하여 미세 조정할 수 있습니다. 이러한 파일은 임계값, 버퍼 및 매칭 로직과 같은 매개변수를 정의합니다:

다음 표에서는 각 매개변수에 대한 설명을 제공합니다:

트래커 임계값 정보

객체 신뢰도 점수가 낮을 경우(즉, 다음보다 낮은 경우) track_high_thresh를 누르면 성공적으로 반환 및 업데이트된 트랙이 없습니다.

매개변수 유효한 값 또는 범위 설명
tracker_type botsort, bytetrack 트래커 유형을 지정합니다. 옵션은 다음과 같습니다. botsort 또는 bytetrack.
track_high_thresh 0.0-1.0 추적 중 사용된 첫 번째 연결에 대한 임계값입니다. 탐지가 기존 트랙과 얼마나 확실하게 일치하는지에 영향을 줍니다.
track_low_thresh 0.0-1.0 추적 중 두 번째 연결에 대한 임계값입니다. 첫 번째 연결이 실패할 때 보다 관대한 기준으로 사용됩니다.
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에 필요한 최소 외관 유사성. 두 감지를 연결하기 위해 시각적으로 얼마나 유사해야 하는지 설정합니다.
with_reid True, False ReID 사용 여부를 나타냅니다. 외형 기반 매칭을 활성화하여 오클루전 전반을 더 잘 추적할 수 있습니다. BoTSORT에서만 지원됩니다.
model auto, yolo11[nsmlx]-cls.pt 사용할 모델을 지정합니다. 기본값은 auto탐지기가 YOLO 경우 기본 기능을 사용하고, 그렇지 않은 경우 yolo11n-cls.pt.

재식별(ReID) 활성화하기

기본적으로 ReID는 성능 오버헤드를 최소화하기 위해 꺼져 있습니다. 사용 설정은 간단합니다. with_reid: True 에서 트래커 구성. 사용자 지정할 수도 있습니다. model 를 사용하여 사용 사례에 따라 정확성과 속도를 절충할 수 있습니다:

  • 기본 기능(model: auto): 이는 ReID용 YOLO 탐지기의 기능을 직접 활용하여 최소한의 오버헤드를 추가합니다. 성능에 큰 영향을 주지 않으면서 일정 수준의 ReID가 필요한 경우에 이상적입니다. 감지기가 기본 기능을 지원하지 않는 경우 자동으로 다음 기능을 사용합니다. yolo11n-cls.pt.
  • YOLO 분류 모델: 분류 모델을 명시적으로 설정할 수 있습니다(예 yolo11n-cls.pt)를 사용하여 ReID 특징을 추출할 수 있습니다. 이렇게 하면 더 많은 변별력을 갖춘 임베딩이 가능하지만 추론 단계가 추가되어 지연 시간이 늘어납니다.

특히 ReID에 별도의 분류 모델을 사용하는 경우 성능을 향상시키기 위해 TensorRT 같은 더 빠른 백엔드로 내보낼 수 있습니다:

ReID 모델을 TensorRT 내보내기

from torch import nn

from ultralytics import YOLO

# Load the classification model
model = YOLO("yolo11n-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 예제

트랙 루프 지속

다음은 다음을 사용하는 Python 스크립트입니다. OpenCV (cv2) 및 YOLO11 를 사용하여 비디오 프레임에서 개체 추적을 실행합니다. 이 스크립트는 필요한 패키지를 이미 설치했다고 가정합니다(opencv-python 그리고 ultralytics). 그리고 persist=True 인수는 트래커에게 현재 이미지 또는 프레임이 시퀀스의 다음 이미지이며 현재 이미지에서 이전 이미지의 트랙을 예상하도록 지시합니다.

추적 기능이 있는 포-루프 스트리밍

import cv2

from ultralytics import YOLO

# Load the YOLO11 model
model = YOLO("yolo11n.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 YOLO11 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("YOLO11 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 YOLO11 을 사용하면 이러한 트랙을 원활하고 효율적으로 플로팅할 수 있습니다.

다음 예제에서는 YOLO11 의 추적 기능을 활용하여 여러 비디오 프레임에서 감지된 객체의 움직임을 플로팅하는 방법을 보여줍니다. 이 스크립트에서는 비디오 파일을 열고 프레임별로 읽은 다음 YOLO 모델을 활용하여 다양한 객체를 식별하고 추적합니다. 감지된 경계 상자의 중심점을 유지하고 연결하여 추적된 객체가 따라간 경로를 나타내는 선을 그릴 수 있습니다.

여러 비디오 프레임에 걸쳐 트랙 플로팅하기

from collections import defaultdict

import cv2
import numpy as np

from ultralytics import YOLO

# Load the YOLO11 model
model = YOLO("yolo11n.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 YOLO11 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.id is not None:
            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("YOLO11 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 이 매개변수를 허용하고 기본 추적 루프를 포함하는 함수입니다. 이 함수는 비디오를 프레임 단위로 읽고 트래커를 실행하여 결과를 표시합니다.

이 예에서는 두 가지 다른 모델이 사용됩니다: yolo11n.pt 그리고 yolo11n-seg.pt를 사용하여 각각 다른 비디오 파일에서 개체를 추적할 수 있습니다. 비디오 파일은 SOURCES.

그리고 daemon=True 매개변수의 threading.Thread 는 메인 프로그램이 완료되는 즉시 이러한 스레드가 닫힌다는 의미입니다. 그런 다음 다음과 같이 스레드를 시작합니다. start() 및 사용 join() 를 설정하여 두 트래커 스레드가 모두 완료될 때까지 메인 스레드가 대기하도록 합니다.

마지막으로 모든 스레드가 작업을 완료하면 결과를 표시하는 창이 다음을 사용하여 닫힙니다. cv2.destroyAllWindows().

멀티 스레드 추적 구현

import threading

import cv2

from ultralytics import YOLO

# Define model names and video sources
MODEL_NAMES = ["yolo11n.pt", "yolo11n-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 YOLO11 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의 트래커 섹션에 기여해 주세요! 여러분의 실제 애플리케이션과 솔루션은 추적 작업을 수행하는 사용자에게 매우 유용할 수 있습니다.

이 섹션에 기여함으로써 Ultralytics YOLO 프레임워크 내에서 사용할 수 있는 추적 솔루션의 범위를 확장하여 커뮤니티에 또 다른 기능과 유틸리티를 추가하는 데 도움을 주실 수 있습니다.

기여를 시작하려면 풀 리퀘스트(PR) 제출에 대한 종합적인 지침이 담긴 기여 가이드를 참조하세요(🛠️). 여러분의 의견을 기다리겠습니다!

함께 Ultralytics YOLO 에코시스템의 추적 기능을 강화해 봅시다 🙏!

자주 묻는 질문

다중 개체 추적이란 무엇이며 Ultralytics YOLO 어떻게 지원하나요?

비디오 분석에서 다중 객체 추적에는 객체를 식별하고 비디오 프레임에서 감지된 각 객체에 대한 고유 ID를 유지하는 작업이 모두 포함됩니다. Ultralytics YOLO 객체 ID와 함께 실시간 추적을 제공하여 보안 감시 및 스포츠 분석과 같은 작업을 용이하게 함으로써 이를 지원합니다. 이 시스템은 YAML 파일을 통해 구성할 수 있는 BoT-SORTByteTrack과 같은 트래커를 사용합니다.

Ultralytics YOLO 에 대한 사용자 지정 트래커를 구성하려면 어떻게 하나요?

기존 트래커 구성 파일을 복사하여 사용자 지정 트래커를 구성할 수 있습니다(예, custom_tracker.yaml)에서 Ultralytics 트래커 구성 디렉토리 로 설정하고 필요에 따라 매개변수를 수정합니다. tracker_type. 추적 모델에서 이 파일을 다음과 같이 사용하세요:

from ultralytics import YOLO

model = YOLO("yolo11n.pt")
results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker="custom_tracker.yaml")
yolo track model=yolo11n.pt 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 = ["yolo11n.pt", "yolo11n-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 YOLO11 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("yolo11n.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("YOLO11 Tracking", annotated_frame)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()

이 스크립트는 시간 경과에 따른 추적 대상의 이동 경로를 보여주는 추적선을 표시하여 대상의 동작과 패턴에 대한 유용한 인사이트를 제공합니다.



📅1 년 전 생성됨 ✏️ 업데이트됨 14일 전

댓글