다중 객체 추적 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"
위의 사용 예에서 볼 수 있듯이 동영상 또는 스트리밍 소스에서 실행되는 모든 감지, 세그먼트 및 포즈 모델에서 추적을 사용할 수 있습니다.
구성
트래커 임계값 정보
객체 신뢰도 점수가 낮을 경우(즉, 다음보다 낮은 경우) track_high_thresh
를 누르면 성공적으로 반환 및 업데이트된 트랙이 없습니다.
추적 인수
추적 구성은 다음과 같이 예측 모드와 속성을 공유합니다. conf
, iou
및 show
. 추가 구성에 대해서는 예측 모델 페이지로 이동합니다.
예
트래커 선택
Ultralytics 를 사용하면 수정된 트래커 구성 파일을 사용할 수도 있습니다. 이렇게 하려면 트래커 구성 파일의 복사본을 만들기만 하면 됩니다(예 custom_tracker.yaml
)에서 ultralytics/cfg/trackers 를 클릭하고 모든 구성을 수정합니다( tracker_type
) 필요에 따라 조정할 수 있습니다.
예
추적 인수의 전체 목록은 ultralytics/cfg/trackers 페이지를 참조하세요.
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
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 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(annotated_frame, [points], isClosed=False, color=(230, 230, 230), thickness=10)
# 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()
멀티 스레드 추적
멀티스레드 추적은 여러 비디오 스트림에서 동시에 객체 추적을 실행할 수 있는 기능을 제공합니다. 이 기능은 여러 대의 감시 카메라에서 여러 개의 비디오 입력을 처리할 때 특히 유용하며, 동시 처리를 통해 효율성과 성능을 크게 향상시킬 수 있습니다.
제공된 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-SORT 및 ByteTrack과 같은 트래커를 사용합니다.
Ultralytics YOLO 에 대한 사용자 지정 트래커를 구성하려면 어떻게 하나요?
기존 트래커 구성 파일을 복사하여 사용자 지정 트래커를 구성할 수 있습니다(예, custom_tracker.yaml
)에서 Ultralytics 트래커 구성 디렉토리 로 설정하고 필요에 따라 매개변수를 수정합니다. tracker_type
. 추적 모델에서 이 파일을 다음과 같이 사용하세요:
예
여러 비디오 스트림에서 동시에 오브젝트 추적을 실행하려면 어떻게 해야 하나요?
여러 비디오 스트림에서 오브젝트 추적을 동시에 실행하려면 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()
이 스크립트는 시간 경과에 따른 추적 대상의 이동 경로를 보여주는 추적선을 표시하여 대상의 동작과 패턴에 대한 유용한 인사이트를 제공합니다.