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")각 매개변수에 대한 자세한 설명은 Tracker Arguments 섹션을 참조하십시오.
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 | 추적 중 두 번째 연관에 사용되는 임계값입니다. 첫 번째 연관이 실패할 때 더 관대한 기준으로 사용됩니다. |
new_track_thresh | 0.0-1.0 | 감지가 기존 트랙과 일치하지 않을 때 새 트랙을 초기화하기 위한 임계값입니다. 새로운 객체가 나타난 것으로 간주되는 시점을 제어합니다. |
track_buffer | >=0 | 제거되기 전에 유실된 트랙을 유지할 프레임 수를 나타내는 버퍼입니다. 값이 높을수록 가림(occlusion)에 대한 허용치가 높아집니다. |
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, 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 모듈을 사용하여 여러 트래커 인스턴스를 동시에 실행합니다. 각 스레드는 하나의 비디오 파일에서 트래커를 실행하며, 모든 스레드는 백그라운드에서 동시에 실행됩니다.
각 스레드가 올바른 매개변수(비디오 파일, 사용할 모델 및 파일 인덱스)를 수신하도록 하기 위해 이러한 매개변수를 허용하고 메인 추적 루프를 포함하는 run_tracker_in_thread 함수를 정의합니다. 이 함수는 비디오를 프레임별로 읽고, 트래커를 실행하며, 결과를 표시합니다.
이 예시에서는 두 가지 모델(yolo26n.pt 및 yolo26n-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()이 예시는 더 많은 스레드를 생성하고 동일한 방법론을 적용하여 더 많은 비디오 파일과 모델을 처리하도록 쉽게 확장할 수 있습니다.
Link to this section새로운 트래커 기여하기#
다중 객체 추적에 능숙하며 Ultralytics YOLO를 사용하여 추적 알고리즘을 성공적으로 구현하거나 적용해 보셨습니까? ultralytics/cfg/trackers의 Trackers 섹션에 기여해 주시기를 권장합니다! 여러분의 실제 애플리케이션과 솔루션은 추적 작업을 수행하는 사용자들에게 매우 소중한 자료가 될 것입니다.
이 섹션에 기여함으로써 여러분은 Ultralytics YOLO 프레임워크 내에서 사용 가능한 추적 솔루션의 범위를 확장하고 커뮤니티를 위한 또 다른 기능과 유용성을 더하게 됩니다.
기여를 시작하려면 PR(Pull Request) 제출에 대한 포괄적인 지침이 담긴 기여 가이드를 참조하십시오 🛠️. 여러분이 어떤 새로운 기술을 선보일지 기대됩니다!
함께 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()이 스크립트는 시간이 지남에 따라 추적된 객체의 이동 경로를 보여주는 추적 선을 그려, 객체 동작과 패턴에 대한 유용한 통찰력을 제공합니다.