YOLO TRACKER이란?
Ultralytics YOLO문서에 확인이 됩니다.
다중객체추적 Ultralytics YOLO이라고불리는것같습니다.
Ultralytics Tracker의 출력은 표준 객체 감지와 일치하긴 하지만 객체id를 따로 부여합니다.
이것을 통해 스트림에서 객체를 쉽게 추적하고 후속 분석까지지 진행할 수 있습니다.
너 이거 왜 공부하는데?
사실 지금 프로젝트를 진행하면서 yolo pose를 사용하고있는데
사람이 1명밖에 없음에도 불구하고 2명으로 잡는 현상이 나타나고 있습니다.
그래서 이 부분을 해결하기 위해서 1명만 잡는걸 어떻게 해야할까? 라는 고민을 하다가 yolopose + tracker까지 하면 보다 잘 잡을 것 같아서 트래커도 공부하게 되었습니다.
https://docs.ultralytics.com/ko/modes/track/
트랙
Ultralytics YOLO 에서 효율적이고 유연하며 사용자 지정 가능한 다중 개체 추적에 대해 알아보세요. 실시간 동영상 스트림을 쉽게 추적하는 방법을 알아보세요.
docs.ultralytics.com
기능 살펴보기
Ultralyics YOLO는 물체 감지 기능을 확장하여 강력하고 다양한 물체 추적을 할 수 있습니다!
1. 실시간 추적 ▶ 고프레임률 동영상에서 오브젝트를 원활하게 추적합니다.
2. 여러 트래커 동시 지원 ▶ 이미 확립된 다양한 추적 알고리즘 중에서 선택할 수 있습니다.
3. 사용자 지정 가능한 트래커 구성 ▶ 다양한 매개변수를 조정해서 특정 요구사항을 충족하도록 추적 알고리즘을 맞춤설정할 수 있습니다.
Ultralyics YOLO는 추적 알고리즘을 사용하고 YAML구성 파일을 전달해서 활성화해서 사용할 수 있습니다.
tracker = tracker_type.yaml:
여기서 yaml이란? 쉽게 말해서 데이터를 쉽고 가독성 좋게 작성하기 위한 설정파일이에요.
주로 구성이나 설정 정보를 저장하는데 사용합니다.
↓ YAML 예시입니다.
tracker:
type: bytetrack # 추적기 종류
conf_thresh: 0.5 # 신뢰도 임계값
iou_thresh: 0.3 # IOU 임계값
persist: True # 객체 ID 유지 여부
특징은 키와 벨류 형식으로 설정값이 정의되고 들여쓰기로 하위설정(계층구조)를 표현합니다.
사용방법
from ultralytics import YOLO
# YOLO 모델 로드
model = YOLO('yolov8n-pose.pt')
# 동영상에서 추적 수행 (ByteTrack 사용)
results = model.track(source='input_video.mp4', tracker='bytetrack.yaml', persist=True)
# 결과 출력
print("추적이 완료되었습니다!")
botsort.yaml을 하면 변경됩니다.
직관적으로 확인해보기
아래 영상 참치 영상으로 트랙커를 추적수행 해보겠습니다.
사실 화질이 좋지 않아서 좋은 결과를 기대하진 않지만 직관적으로 어떤 변화가 보이는지 확인하기 위함이니
참고해주세요!
yaml을 입힐때 각 프레임은 898로 잡히고
tracker | persist (객체id유지) |
결과 |
bytetrack | False | ![]() |
bytetrack | True | ![]() |
botsort | False | ![]() |
persist=False를 하면 앞에 id값이 나타난다
근데 tracker 의 차이는 모르겠다.그래서 gpt에게 좀 물어보니
bytetrack | 빠르고 간단하며 실시간 처리에 유리. |
botsort | ReID를 활용해 더 높은 정확도를 제공하지만 조금 더 느림. |
이라고 합니다. 조금 세밀하거나 세심한 부분에서 차이가 있는것이기때문에
저는 가림이 있는경우 없는경우로 나뉘어서 알아두려고 합니다.
복잡한 환경이나 객체가 자주 가려지는 상화엥서는 botsort가 더 낫다는 부분을 학습한 내용으로 알아가겠습니다..
python 사용 예시 코드
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
동영상 stream에서 tracker을 실행하려면 YOLO11n, YOLO11n-seg, YOLO11n-pose을 사용하면 됩니다.
인수 공유
YOLO에 있는 conf, iou, show에 대한 것은 그대로 가져올 수 있습니다. 아래는 예시코드입니다.
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)
또한 트래커의 구성파일을 서낵할 수 있습니다.
추적인수의 전체 인수는 아래와 같습니다.
botsort
# Ultralytics YOLO 🚀, AGPL-3.0 license
# Default YOLO tracker settings for BoT-SORT tracker https://github.com/NirAharon/BoT-SORT
tracker_type: botsort # tracker type, ['botsort', 'bytetrack']
track_high_thresh: 0.25 # threshold for the first association
track_low_thresh: 0.1 # threshold for the second association
new_track_thresh: 0.25 # threshold for init new track if the detection does not match any tracks
track_buffer: 30 # buffer to calculate the time when to remove tracks
match_thresh: 0.8 # threshold for matching tracks
fuse_score: True # Whether to fuse confidence scores with the iou distances before matching
# min_box_area: 10 # threshold for min box areas(for tracker evaluation, not used for now)
# BoT-SORT settings
gmc_method: sparseOptFlow # method of global motion compensation
# ReID model related thresh (not supported yet)
proximity_thresh: 0.5
appearance_thresh: 0.25
with_reid: False
bytetrack
# Ultralytics YOLO 🚀, AGPL-3.0 license
# Default YOLO tracker settings for ByteTrack tracker https://github.com/ifzhang/ByteTrack
tracker_type: bytetrack # tracker type, ['botsort', 'bytetrack']
track_high_thresh: 0.25 # threshold for the first association
track_low_thresh: 0.1 # threshold for the second association
new_track_thresh: 0.25 # threshold for init new track if the detection does not match any tracks
track_buffer: 30 # buffer to calculate the time when to remove tracks
match_thresh: 0.8 # threshold for matching tracks
fuse_score: True # Whether to fuse confidence scores with the iou distances before matching
# min_box_area: 10 # threshold for min box areas(for tracker evaluation, not used for now)
그리고 트랙의 가장 재밌어보였던 부분이 있는데 바로 시간 경과에 따른 트랙 플로팅입니다.
감지된 객체의 움직임을 플로팅하는 방법을 보여준다고 합니다. 그래서 객체가 따라간 경로를 나타내는 선을 그릴 수 있다고합니다.
!pip install ultralytics
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 = "/content/166115-835290832_tiny.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 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)
import matplotlib.pyplot as plt
# Display the frame using Matplotlib
plt.imshow(cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.show()
# 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()
이런식으로 선이 그려지면서 트래킹이 되는 모습을 확인할 수 있습니다.
물론 멀티(여러비디오)도 가능하니 꼭 기억해두었다가 사용할 일이 있을때 잘 써봐야겠습니다.
'모델 논문, 학습' 카테고리의 다른 글
모델 GITHUB참고 (0) | 2025.02.23 |
---|---|
Vision Transformer(ViT) 논문 리뷰(직역) (0) | 2025.02.18 |
You Only Look Once:Unified, Real-Time Object Detection (0) | 2024.12.03 |
[논문] alexnet 알렉스넷 논문 (0) | 2024.10.16 |