Bắt đầu

Theo dõi nhiều đối tượng bằng Ultralytics YOLO

YOLO multi-object tracking with trajectory paths

Tracking nhiều đối tượng trong phân tích video xác định vị trí và lớp của đối tượng trong mỗi khung hình, đồng thời duy trì ID riêng cho từng đối tượng được phát hiện khi video tiếp diễn. Các ứng dụng trải rộng từ giám sát và an ninh đến phân tích thể thao thời gian thực.

Xem bản xem trước YOLO27 chưa phát hành để biết về hỗ trợ theo dõi dự kiến.

Bộ theo dõi: OC-SORT, Deep OC-SORT, FastTracker, TrackTrack

Bắt đầu từ ultralytics 8.4.63, OC-SORT, Deep OC-SORT, FastTracker và TrackTrack được cung cấp cùng với BoT-SORT và ByteTrack.

Tại sao nên chọn Ultralytics YOLO để theo dõi đối tượng?#

Đầu ra từ các tracker của Ultralytics nhất quán với đầu ra phát hiện đối tượng tiêu chuẩn, nhưng có thêm ID đối tượng. Điều này giúp dễ dàng theo dõi đối tượng trong luồng video và thực hiện phân tích tiếp theo. Những lý do chính để sử dụng Ultralytics YOLO cho tracking đối tượng:

  • Hiệu quả: Xử lý luồng video theo thời gian thực mà không ảnh hưởng đến độ chính xác.
  • Linh hoạt: Hỗ trợ nhiều thuật toán tracking và cấu hình.
  • Dễ sử dụng: API Python và các tùy chọn CLI đơn giản giúp tích hợp và triển khai nhanh chóng.
  • Khả năng tùy chỉnh: Dễ sử dụng với các model YOLO được huấn luyện tùy chỉnh, cho phép tích hợp vào các ứng dụng chuyên biệt theo lĩnh vực.


Xem: Cách theo dõi nhiều đối tượng bằng Ultralytics YOLO26 | BoT-SORT và ByteTrack | VisionAI 🚀

Ứng dụng thực tế#

Giao thông vận tảiBán lẻNuôi trồng thủy sản
Theo dõi phương tiệnTheo dõi ngườiTheo dõi cá

Bắt đầu nhanh#

Chạy theo dõi trên video bằng tracker TrackTrack mặc định. Chuyển sang tracker khác bằng cách thay đổi đối số tracker.

Ví dụ
from ultralytics import YOLO

model = YOLO("yolo26n.pt")

# Tracker mặc định (TrackTrack)
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True)

# Chuyển sang ByteTrack
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")

Để chạy tracker trên luồng video, hãy sử dụng model Detect, Segment, Pose hoặc OBB đã huấn luyện, chẳng hạn YOLO26n, YOLO26n-seg, YOLO26n-pose hoặc YOLO26n-obb; tất cả đều có trong bộ sưu tập YOLO26 trên Ultralytics Platform. Bạn có thể huấn luyện model tùy chỉnh cục bộ hoặc bằng dịch vụ huấn luyện đám mây của Ultralytics Platform.

Ví dụ
from ultralytics import YOLO

# Nạp model chính thức hoặc model tùy chỉnh
model = YOLO("yolo26n.pt")  # Nạp model Detect chính thức
model = YOLO("yolo26n-seg.pt")  # Nạp model Segment chính thức
model = YOLO("yolo26n-pose.pt")  # Nạp model Pose chính thức
model = YOLO("path/to/best.pt")  # Nạp model được huấn luyện tùy chỉnh

# Thực hiện theo dõi bằng model
results = model.track("https://youtu.be/LNwODJXcvt4", show=True)  # Theo dõi bằng tracker mặc định
results = model.track("https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")  # bằng ByteTrack

Các tracker được hỗ trợ#

Ultralytics YOLO đi kèm sáu tracker tích hợp sẵn. Bật một tracker bằng cách truyền tệp cấu hình YAML của tracker đó vào đối số tracker.

TrackerTệp cấu hìnhModel chuyển độngNgoại hình / ReIDBù chuyển động cameraXử lý che khuất
BoT-SORTbotsort.yamlKalman tuyến tínhTùy chọn (with_reid)Có thể cấu hình (gmc_method)Bộ đệm theo dõi + liên kết lại ReID
ByteTrackbytetrack.yamlKalman tuyến tínhKhông cóKhôngCứu vãn hai giai đoạn cho đối tượng có độ tin cậy thấp
OC-SORTocsort.yamlKalman lấy quan sát làm trung tâmKhông cóKhôngORU, OCM, OCR cập nhật lại từ quan sát gần nhất
Deep OC-SORTdeepocsort.yamlKalman lấy quan sát làm trung tâmTùy chọn (with_reid)Có thể cấu hình (gmc_method)OC-SORT + EMA ngoại hình thích ứng tùy chọn
FastTrackerfasttrack.yamlKalman tuyến tính + quay luiKhông cóKhôngQuay lui Kalman + mở rộng bbox khi bị che khuất
TrackTracktracktrack.yamlKalman tuyến tính (NSA)Tùy chọn (with_reid)Có thể cấu hình (gmc_method)Liên kết đa tín hiệu lặp lại + TAI

Nên dùng tracker nào?#

Dùng sơ đồ này để chọn điểm bắt đầu; tracktrack.yaml được sử dụng khi bạn không truyền tracker:

  1. Cần baseline nhanh nhất, đơn giản nhất? → ByteTrack (không ReID, không bù chuyển động camera, chi phí xử lý tối thiểu).
  2. Video quay bằng tay, drone hoặc camera chuyển động? → BoT-SORT (bổ sung bù chuyển động camera và ReID tùy chọn).
  3. Chuyển động phi tuyến (thể thao, khiêu vũ, đổi hướng đột ngột) và không dùng ReID? → OC-SORT (hiệu chỉnh lấy quan sát làm trung tâm mà không tốn chi phí xử lý ngoại hình).
  4. Cảnh đông người, camera chuyển động, trong đó nhầm lẫn ID là vấn đề chính? → Deep OC-SORT hoặc TrackTrack (cả hai đều hỗ trợ so khớp ngoại hình tùy chọn; TrackTrack còn bổ sung liên kết đa tín hiệu và loại bỏ ID trùng lặp).
  5. Thường xuyên chồng lấp một phần trong thời gian thực, không có ngân sách cho ReID? → FastTracker (biến thể ByteTrack nhận biết che khuất, có khả năng quay lui Kalman).

Chuyển đổi tracker#

Truyền tên tệp cấu hình tracker vào tracker=. Các phần code khác giữ nguyên.

Ví dụ
from ultralytics import YOLO

model = YOLO("yolo26n.pt")

results = model.track(source="path/to/video.mp4", tracker="bytetrack.yaml")
results = model.track(source="path/to/video.mp4", tracker="ocsort.yaml")
results = model.track(source="path/to/video.mp4", tracker="tracktrack.yaml")

Cấu hình#

Các đối số theo dõi#

Cấu hình tracking dùng chung các đối số inference với chế độ Predict, chẳng hạn conf, iou và show.

Ví dụ
from ultralytics import YOLO

# Cấu hình các tham số theo dõi và chạy tracker
model = YOLO("yolo26n.pt")
results = model.track(source="https://youtu.be/LNwODJXcvt4", conf=0.1, iou=0.5, show=True)

Cấu hình tracker tùy chỉnh#

Để sử dụng cấu hình tracker đã chỉnh sửa, hãy sao chép tệp cấu hình tracker (ví dụ: thành custom_tracker.yaml) từ ultralytics/cfg/trackers rồi sửa đổi mọi thiết lập ngoại trừ tracker_type.

Ví dụ
from ultralytics import YOLO

# Nạp model và chạy tracker bằng tệp cấu hình tùy chỉnh
model = YOLO("yolo26n.pt")
results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker="custom_tracker.yaml")

Các đối số dùng chung của tracker#

Các tham số sau đây phổ biến trong hầu hết tệp YAML của tracker; không phải tham số nào cũng có trong mọi cấu hình:

Thông tin về ngưỡng của tracker

Các kết quả phát hiện có giá trị bằng hoặc cao hơn track_high_thresh sẽ đi vào giai đoạn liên kết đầu tiên. Các kết quả phát hiện nằm giữa track_low_thresh và track_high_thresh có thể khôi phục track hiện có khi tracker được chọn bật liên kết độ tin cậy thấp, nhưng không khởi tạo track mới. Các kết quả phát hiện có giá trị bằng hoặc thấp hơn track_low_thresh sẽ bị bỏ qua.

Tham sốGiá trị hoặc phạm vi hợp lệMô tả
tracker_typebotsort, bytetrack, ocsort, deepocsort, fasttrack, tracktrackChỉ định loại tracker.
track_high_thresh0.0-1.0Ngưỡng cho lần liên kết đầu tiên. Ảnh hưởng đến mức độ chắc chắn khi ghép một detection với track hiện có.
track_low_thresh0.0-1.0Giới hạn dưới cho các detection khôi phục có độ tin cậy thấp. OC-SORT và Deep OC-SORT chỉ sử dụng các detection này khi use_byte: True; TrackTrack đưa chúng vào nhóm liên kết bị phạt.
new_track_thresh0.0-1.0Ngưỡng để khởi tạo track mới nếu detection không khớp với bất kỳ track hiện có nào.
track_buffer>=0Số frame giữ các track bị mất trước khi xóa. Giá trị cao hơn giúp chịu được hiện tượng che khuất tốt hơn.
match_thresh0.0-1.0Ngưỡng để ghép track. Giá trị cao hơn giúp việc ghép dễ dãi hơn.
fuse_scoreTrue, FalseCó kết hợp điểm confidence với khoảng cách IoU trước khi ghép hay không.
gmc_methodsparseOptFlow, orb, sift, ecc, nonePhương pháp bù chuyển động toàn cục. Giúp xử lý chuyển động của camera.
proximity_thresh0.0-1.0IoU tối thiểu cần có để một kết quả ghép ReID được xem là hợp lệ. Đảm bảo độ gần về không gian trước khi sử dụng đặc trưng ngoại hình.
appearance_thresh0.0-1.0Độ tương đồng ngoại hình chuẩn hóa tối thiểu cần có cho ReID.
with_reidTrue, FalseBật ghép dựa trên ngoại hình để theo dõi tốt hơn qua các lần che khuất. Được BoT-SORT, Deep OC-SORT và TrackTrack hỗ trợ.
modelĐường dẫn đến model auto hoặc model ReID tương thíchModel ReID. auto sử dụng đặc trưng backbone YOLO gốc khi có; nếu không, sẽ chuyển sang yolo26n-cls.pt. Encoder tùy chỉnh có thể là checkpoint .pt hoặc model đã export như .torchscript, .onnx, .engine hoặc thư mục model OpenVINO.

Các tham số riêng của tracker#

Mỗi thuật toán cung cấp thêm các tùy chọn bên cạnh những tham số dùng chung. Xem phần riêng của từng tracker bên dưới để biết mô tả và hướng dẫn tinh chỉnh, hoặc tham khảo trực tiếp các file cấu hình:

Bật Re-Identification (ReID)#

ReID bị tắt theo mặc định để giảm thiểu chi phí xử lý. Bật tính năng này bằng cách đặt with_reid: True trong tệp cấu hình tracker.

Các tùy chọn model ReID:

  • model: auto — Sử dụng đặc trưng detector YOLO gốc, chỉ thêm overhead tối thiểu. Phù hợp khi cần một mức ReID nhất định mà không ảnh hưởng nhiều đến hiệu năng. Chuyển sang yolo26n-cls.pt nếu detector không cung cấp các đặc trưng tương thích.
  • Model ReID tùy chỉnh — Trỏ model: đến checkpoint .pt hoặc model embedding đã export tương thích, chẳng hạn .torchscript, .onnx, .engine hoặc thư mục model OpenVINO. Model đã export được tải thông qua AutoBackend và phải xuất trực tiếp tensor embedding.

Encoder ONNX sẵn sàng sử dụng được phát hành cho mọi kích thước model. Đặt model: thành một trong các tên này để file tự động được tải xuống khi tracker chạy lần đầu (tương tự cách tải trọng số YOLO) — không cần export hoặc tải xuống thủ công:

# In your tracker config (e.g. tracktrack.yaml)
with_reid: True
model: yolo26n-reid.onnx # downloaded on first use; swap n→s/m/l/x for a larger encoder
Modelkích thước
(pixel)
tham số
(M)
FLOPs
(B)
YOLO26n-reid.onnx4482.82.0
YOLO26s-reid.onnx4487.56.6
YOLO26m-reid.onnx44812.420.1
YOLO26l-reid.onnx44815.325.2
YOLO26x-reid.onnx44832.755.9
ReID chỉ dùng cho tracking

Hiện chỉ có các encoder ReID ONNX cho nhánh ngoại hình của tracker. Các chế độ ReID train, val và predict, cùng với các quy trình export ReID chuyên biệt, vẫn đang được phát triển.

Để tăng hiệu năng khi dùng model phân loại riêng, hãy export model sang backend nhanh hơn như TensorRT:

Export model ReID sang TensorRT
from torch import nn

from ultralytics import YOLO

# Tải model phân loại
model = YOLO("yolo26n-cls.pt")

# Thêm lớp average pooling
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 sang TensorRT
model.export(format="engine", quantize=16, dynamic=True, batch=32)

Sau khi export, trỏ đến đường dẫn model TensorRT trong cấu hình tracker.

Chi tiết về tracker#

Các phần bên dưới mô tả thiết kế, tham số cụ thể và mẹo tinh chỉnh cho từng tracker.



Xem: Bộ theo dõi đối tượng nào hoạt động tốt hơn? | Tốc độ, FPS và độ ổn định ID | Ultralytics YOLO26 📊

BoT-SORT#

BoT-SORT (Aharon và cộng sự, 2022) mở rộng ByteTrack bằng cách bổ sung bù chuyển động camera và ReID tùy chọn:

  • Bù chuyển động camera (CMC): áp dụng phép biến đổi affine ước lượng ở mỗi frame (mặc định dùng sparse optical flow; cũng có ORB / ECC) cho các trạng thái Kalman trước khi ghép IoU.
  • ReID tùy chọn: có thể kết hợp embedding ngoại hình vào ma trận chi phí. Mặc định bị tắt; bật bằng with_reid: True.

Phù hợp nhất với: tracking đa dụng, đặc biệt là khi camera di chuyển. Chỉ thêm ReID khi đám đông có ngoại hình tương tự gây ra hiện tượng đổi ID.

Các tham số riêng của BoT-SORT:

Tham sốGiá trị hoặc phạm vi hợp lệMô tả
gmc_methodsparseOptFlow, orb, sift, ecc, noneBackend bù chuyển động camera. sparseOptFlow là mặc định. none tắt CMC.
with_reidTrue, FalseBật ghép dựa trên ngoại hình. Mặc định tắt.
modelĐường dẫn đến model auto hoặc model ReID tương thíchauto sử dụng đặc trưng YOLO gốc khi có; model tùy chỉnh có thể là checkpoint .pt hoặc bản export tương thích.
proximity_thresh0.0-1.0IoU tối thiểu trước khi xét đến đặc trưng ngoại hình.
appearance_thresh0.0-1.0Độ tương đồng ngoại hình chuẩn hóa tối thiểu cần có để ghép ReID. Tăng giá trị này để ghép chặt chẽ hơn.

Mẹo tinh chỉnh:

  • Camera tĩnh: đặt gmc_method: none để tiết kiệm vài ms/frame.
  • Camera chuyển động mạnh: giữ sparseOptFlow; ecc chính xác hơn nhưng chậm hơn.
  • Đám đông có ngoại hình tương tự: bật with_reid: True và tăng appearance_thresh (ví dụ: 0.85+).

ByteTrack#

ByteTrack (Zhang và cộng sự, ECCV 2022) là baseline gọn nhẹ. Thuật toán sử dụng Kalman tuyến tính + IoU với quy trình liên kết hai giai đoạn:

  • Giai đoạn 1: ghép các detection có điểm số cao với các track đang hoạt động.
  • Giai đoạn 2: thử ghép lại các track chưa được ghép với detection có điểm số thấp để khôi phục qua những lần che khuất một phần trong thời gian ngắn.

Không có model ngoại hình và không có chức năng bù chuyển động camera.

Phù hợp nhất với: camera tĩnh hoặc gần như tĩnh, nơi chi phí detector chiếm phần lớn và bạn muốn giảm overhead của tracker xuống mức tối thiểu.

Các tham số riêng của ByteTrack: Không có tham số nào ngoài các tham số tracker dùng chung.

Mẹo tinh chỉnh:

  • Detector nhiễu: giảm track_low_thresh để giai đoạn hai có thêm ứng viên.
  • Detector có recall cao: tăng track_high_thresh để giảm ID bị phân mảnh.
  • ID thường xuyên chập chờn: tăng track_buffer để các track bị bỏ lỡ trong thời gian ngắn vẫn được giữ lại.

OC-SORT#

OC-SORT (Cao và cộng sự, CVPR 2023) là phiên bản mở rộng của SORT lấy quan sát làm trung tâm. Thuật toán giữ nguyên thiết kế gọn nhẹ của SORT (không dùng đặc trưng ngoại hình) và bổ sung ba hiệu chỉnh:

  • Cập nhật lại lấy quan sát làm trung tâm (ORU): phát lại quỹ đạo ảo giữa quan sát cuối cùng và detection hiện tại, chạy lại bước cập nhật Kalman để hiệu chỉnh vận tốc bị lệch.
  • Động lượng lấy quan sát làm trung tâm (OCM): phạt các detection di chuyển sai hướng thông qua thành phần chi phí nhất quán vận tốc.
  • Khôi phục lấy quan sát làm trung tâm (OCR): kiểm tra lại các detection chưa được ghép với các track vừa bị mất, sử dụng quan sát cuối cùng thay vì trạng thái dự đoán.

Phù hợp nhất với: chuyển động phi tuyến mà không phải chịu chi phí của model ReID.

Các tham số riêng của OC-SORT:

Tham sốGiá trị hoặc phạm vi hợp lệMô tả
delta_t>=1Cửa sổ thời gian (frame) dùng để tính hướng vận tốc trong OCM. Giá trị lớn hơn giúp làm mượt nhiều hơn.
inertia0.0-1.0Trọng số của chi phí nhất quán vận tốc. Giá trị cao hơn phạt các thay đổi hướng đột ngột nặng hơn.
use_byteTrue, FalseBật lượt liên kết thứ hai kiểu ByteTrack trên các detection có độ tin cậy thấp.

Mẹo tinh chỉnh:

  • Chuyển động phi tuyến: tăng inertia (ví dụ: 0.3-0.4).
  • Detection thưa: bật use_byte: True.
  • Che khuất kéo dài: tăng track_buffer để OCR có thêm track bị mất để liên kết lại.

Với model OBB, OCR sử dụng BBox có hướng do Kalman dự đoán vì lịch sử quan sát cuối cùng có hướng không được lưu giữ.

Deep OC-SORT#

Deep OC-SORT bổ sung thông tin ngoại hình và bù chuyển động camera cho OC-SORT:

  • Ghép ngoại hình: khoảng cách embedding cosine được giới hạn theo độ chồng lấp và kết hợp với chi phí chuyển động.
  • EMA ngoại hình động: embedding của track được cập nhật bằng EMA với hệ số làm mượt thích ứng theo độ tin cậy của detection.
  • Bù chuyển động camera: các trạng thái Kalman được biến đổi giữa các frame thông qua sparse optical flow, ORB hoặc ECC.

Phù hợp nhất với: cảnh đông người hoặc camera di chuyển, nơi thường xảy ra đổi ID giữa các đối tượng có ngoại hình khác nhau nhưng ở gần nhau về mặt không gian.

Các tham số riêng của Deep OC-SORT:

Tham sốGiá trị hoặc phạm vi hợp lệMô tả
with_reidTrue, FalseBật ghép dựa trên ngoại hình. Mặc định tắt.
modelĐường dẫn đến model auto hoặc model ReID tương thíchauto sử dụng đặc trưng YOLO gốc khi có; model tùy chỉnh có thể là checkpoint .pt hoặc bản export tương thích.
proximity_thresh0.0-1.0IoU tối thiểu trước khi xét đến đặc trưng ngoại hình.
appearance_thresh0.0-1.0Độ tương đồng ngoại hình chuẩn hóa tối thiểu cần có để ghép ReID.
alpha_fixed_emb0.0-1.0Hệ số EMA cơ sở cho các bản cập nhật embedding của track. Giá trị cao hơn giúp giữ embedding cũ lâu hơn.
gmc_methodsparseOptFlow, orb, sift, ecc, nonePhương pháp bù chuyển động toàn cục.
delta_t>=1Cửa sổ thời gian (frame) dùng để tính hướng vận tốc trong OCM (được kế thừa từ OC-SORT).
inertia0.0-1.0Trọng số của chi phí nhất quán vận tốc (được kế thừa từ OC-SORT).
use_byteTrue, FalseBật lượt liên kết thứ hai kiểu ByteTrack trên các detection có độ tin cậy thấp (được kế thừa từ OC-SORT).

Mẹo tinh chỉnh:

  • Đổi ID trong đám đông: tăng appearance_thresh (ví dụ: 0.92-0.95) và tăng alpha_fixed_emb để embedding thích ứng chậm hơn.
  • Camera di chuyển: đặt gmc_method: sparseOptFlow (Deep OC-SORT mặc định dùng none).
  • Giảm độ trễ: giữ with_reid: False (mặc định) để chỉ dùng chuyển động + CMC; chỉ bật ReID khi lỗi chủ yếu do đổi ID.

FastTracker#

FastTracker là biến thể ByteTrack có nhận biết che khuất, không dùng model ngoại hình:

  • Phát hiện che khuất: đánh dấu track bị che khuất khi tỷ lệ bị các track đang hoạt động khác che phủ vượt quá occ_cover_thresh.
  • Khôi phục Kalman khi bị che khuất: khôi phục trạng thái Kalman về một frame trước khi bị che khuất bằng lịch sử được lưu trong ring buffer.
  • Giảm chấn chuyển động và mở rộng vùng tìm kiếm: vận tốc được giảm chấn và bbox dự đoán được phóng to khi bị che khuất.
  • Chặn khởi tạo theo IoU: ngăn track mới được tạo chồng lên các track đang hoạt động.

Phù hợp nhất với: pipeline detection thời gian thực có các mục tiêu thường xuyên chồng lấp nhau (đám đông, hàng chờ, thể thao).

Các tham số dành riêng cho FastTracker:

Tham sốGiá trị hoặc phạm vi hợp lệMô tả
reset_velocity_offset_occ>=0Số frame lịch sử lùi lại để khôi phục vận tốc Kalman khi bắt đầu bị che khuất.
reset_pos_offset_occ>=0Số frame lịch sử lùi lại để khôi phục vị trí Kalman khi bắt đầu bị che khuất.
enlarge_bbox_occ>=1.0Hệ số tỷ lệ chiều cao được áp dụng cho bbox dự đoán trong thời gian bị che khuất (chiều rộng được điều chỉnh theo tỷ lệ khung hình XYAH).
dampen_motion_occ0.0-1.0Hệ số nhân vận tốc trong thời gian bị che khuất. Giá trị thấp hơn khiến track "chậm lại" khi đi qua vùng bị che khuất.
active_occ_to_lost_thresh>=1Số frame liên tiếp tối đa bị che khuất trước khi chuyển một track đang hoạt động sang trạng thái mất.
occ_cover_thresh0.0-1.0Tỷ lệ diện tích của một track bị track đang hoạt động khác che phủ để xác định trạng thái che khuất.
occ_reappear_window>=0Số frame mà một track bị mất do vừa bị che khuất vẫn được ưu tiên tìm lại.
init_iou_suppress0.0-1.0Ngăn khởi tạo track mới nếu IoU của track đó với bất kỳ track đang hoạt động nào vượt quá giá trị này. Đặt thành 1.0 để tắt.

Mẹo tinh chỉnh:

  • Thường xuyên bị che khuất một phần: giảm occ_cover_thresh (ví dụ: 0.5-0.6).
  • ID trùng lặp quanh vùng chồng lấp: giảm init_iou_suppress (ví dụ: 0.5).
  • Bị che khuất lâu: tăng đồng thời occ_reappear_window và track_buffer.
  • Đối tượng di chuyển nhanh: tăng dampen_motion_occ (tiến gần hơn đến 1.0); chỉ tăng enlarge_bbox_occ khi vùng tìm kiếm rộng hơn giúp cải thiện khả năng khôi phục.

TrackTrack#

TrackTrack (Shim et al., CVPR 2025) là tracker mặc định. TrackTrack suy luận từ góc nhìn của từng track bằng phương pháp liên kết lặp đa tín hiệu:

  • Liên kết dựa trên góc nhìn của track (TPA): kết hợp HMIoU, khoảng cách cosine ReID tùy chọn, khoảng cách chiếu độ tin cậy và khoảng cách góc ở các góc hộp. Việc gán được giải bằng cách lặp lại với ngưỡng nới lỏng dần.
  • Khởi tạo nhận biết track (TAI): loại bỏ các track mới được tạo trùng lặp trước khi tạo ID mới.

Phù hợp nhất với: cảnh đông người thường xuyên bị che khuất, nơi ID trùng lặp là vấn đề.

Các tham số dành riêng cho TrackTrack:

Tham sốGiá trị hoặc phạm vi hợp lệMô tả
iou_weight0.0-1.0Trọng số của khoảng cách HMIoU khi bật ReID; nếu không, HMIoU được sử dụng trực tiếp.
reid_weight0.0-1.0Trọng số của khoảng cách cosine ReID khi bật ReID; nếu không, tham số này bị bỏ qua.
conf_weight0.0-1.0Trọng số của khoảng cách chiếu độ tin cậy.
angle_weight0.0-1.0Trọng số của khoảng cách góc ở các góc hộp.
penalty_p0.0-1.0Mức phạt chi phí đối với các detection có độ tin cậy thấp.
penalty_q0.0-1.0Mức phạt chi phí đối với các detection được khôi phục bằng NMS phụ.
reduce_step0.0-1.0Mức nới lỏng ngưỡng khớp ở mỗi vòng lặp.
tai_thr0.0-1.0Ngưỡng IoU cho NMS của Khởi tạo nhận biết track.
min_track_len>=0Độ dài lịch sử tối thiểu trước khi xác nhận một track mới.
lost_match_thr0.0-1.0Ngưỡng chi phí nới lỏng hơn cho lượt liên kết lại các track mất; 0 sẽ tắt tính năng này.
with_reidTrue, FalseBật khớp ngoại hình bằng cosine-ReID (sử dụng các feature YOLO gốc). Mặc định tắt.
modelĐường dẫn đến model auto hoặc model ReID tương thíchauto sử dụng đặc trưng YOLO gốc khi có; model tùy chỉnh có thể là checkpoint .pt hoặc bản export tương thích.
gmc_methodsparseOptFlow, orb, sift, ecc, nonePhương pháp bù chuyển động toàn cục.

Mẹo tinh chỉnh:

  • Người đi bộ trong cảnh đông đúc: giảm tai_thr (ví dụ: 0.45) để loại bỏ thêm các track mới trùng lặp; tăng track_buffer để xử lý tình trạng che khuất lâu hơn.
  • Chuyển động camera nhanh: giữ gmc_method: sparseOptFlow ở trạng thái bật.
  • Đối tượng nhỏ/nhanh: tăng nhẹ angle_weight và giảm min_track_len.
  • Chỉ bật ReID khi cần: ReID làm tăng chi phí suy luận; với các trường hợp bị che khuất trong thời gian ngắn, chi phí đa tín hiệu mặc định thường là đủ.

Với các model Segment và Pose, TrackTrack bỏ qua bước khôi phục detection bằng loose-NMS để đảm bảo mask và keypoint vẫn khớp với detection tương ứng.

Ví dụ Python#



Xem: Cách xây dựng tính năng theo dõi đối tượng tương tác với Ultralytics YOLO26: Hoàn thành trong vài phút | Python!

Vòng lặp duy trì track#

Sau đây là một script Python sử dụng OpenCV (cv2) và YOLO26 để theo dõi đối tượng trên các frame video. Script này giả định các package cần thiết (opencv-python và ultralytics) đã được cài đặt. Tham số persist=True cho tracker biết ảnh hoặc frame hiện tại là frame tiếp theo trong một chuỗi và cần tìm các track từ ảnh trước đó trong ảnh hiện tại.

Duy trì track và chọn tracker

Chỉ sử dụng persist=True khi truyền các frame liên tiếp từ cùng một luồng video vào model.track(). Cách này cho phép tracker tái sử dụng trạng thái từ các frame trước đó và duy trì ID track nhất quán theo thời gian. Không sử dụng persist=True cho các ảnh không liên quan hoặc luồng khác, vì trạng thái track trước đó có thể được giữ lại.

Bạn cũng có thể chọn backend tracker bằng cách truyền tệp cấu hình tracker, chẳng hạn như tracker="botsort.yaml", tracker="bytetrack.yaml" hoặc tracker="tracktrack.yaml".

Vòng lặp for dạng streaming với tracking
import cv2

from ultralytics import YOLO

# Tải model YOLO26
model = YOLO("yolo26n.pt")

# # Mở tệp video
video_path = "path/to/video.mp4"
cap = cv2.VideoCapture(video_path)

# # Lặp qua các frame video
while cap.isOpened():
    # # Đọc một frame từ video
    success, frame = cap.read()

    if success:
        # Chạy tracking YOLO26 trên frame, duy trì track giữa các frame
        # và sử dụng backend tracker BoT-SORT
        results = model.track(frame, persist=True, tracker="botsort.yaml")

        # # Trực quan hóa kết quả trên frame
        annotated_frame = results[0].plot()

        # # Hiển thị frame đã chú thích
        cv2.imshow("YOLO26 Tracking", annotated_frame)

        # # Thoát vòng lặp nếu nhấn 'q'
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # # Thoát vòng lặp nếu đã đến cuối video
        break

# # Giải phóng đối tượng capture video và đóng cửa sổ hiển thị
cap.release()
cv2.destroyAllWindows()

Lưu ý thay đổi từ model(frame) sang model.track(frame), giúp bật tracking đối tượng thay vì chỉ phát hiện đơn thuần. Script đã chỉnh sửa này sẽ chạy tracker trên từng khung hình video, trực quan hóa kết quả và hiển thị chúng trong cửa sổ. Có thể thoát vòng lặp bằng cách nhấn 'q'.

Vẽ track theo thời gian#

Trực quan hóa các track của đối tượng qua những khung hình liên tiếp có thể cung cấp thông tin hữu ích về quy luật di chuyển và hành vi của các đối tượng được phát hiện trong video. Ultralytics YOLO26 giúp việc vẽ các track này trở nên đơn giản.

Ví dụ sau sử dụng tracking của YOLO26 để vẽ chuyển động của các đối tượng được phát hiện qua nhiều khung hình video. Script mở tệp video, đọc từng khung hình và dùng model YOLO để xác định cũng như theo dõi đối tượng. Bằng cách lưu lại tâm của các bounding box được phát hiện và nối các tâm này, script vẽ các đường biểu thị quỹ đạo của những đối tượng được theo dõi.

Vẽ track qua nhiều frame video
from collections import defaultdict

import cv2
import numpy as np

from ultralytics import YOLO

# Tải model YOLO26
model = YOLO("yolo26n.pt")

# # Mở tệp video
video_path = "path/to/video.mp4"
cap = cv2.VideoCapture(video_path)

# Lưu lịch sử track
track_history = defaultdict(list)

# # Lặp qua các frame video
while cap.isOpened():
    # # Đọc một frame từ video
    success, frame = cap.read()

    if success:
        # Chạy tracking YOLO26 trên frame, duy trì track giữa các frame
        result = model.track(frame, persist=True)[0]

        # Lấy các box và ID track
        if result.boxes and result.boxes.is_track:
            boxes = result.boxes.xywh.cpu()
            track_ids = result.boxes.id.int().cpu().tolist()

            # Trực quan hóa kết quả trên frame
            frame = result.plot()

            # Vẽ các track
            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)))  # tọa độ tâm x, y
                if len(track) > 30:  # giữ lại 30 track trong 30 frame
                    track.pop(0)

                # Vẽ các đường tracking
                points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
                cv2.polylines(frame, [points], isClosed=False, color=(230, 230, 230), thickness=10)

        # # Hiển thị frame đã chú thích
        cv2.imshow("YOLO26 Tracking", frame)

        # # Thoát vòng lặp nếu nhấn 'q'
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # # Thoát vòng lặp nếu đã đến cuối video
        break

# # Giải phóng đối tượng capture video và đóng cửa sổ hiển thị
cap.release()
cv2.destroyAllWindows()

Tracking đa luồng#

Tracking đa luồng cho phép chạy tracking đối tượng đồng thời trên nhiều luồng video. Tính năng này đặc biệt hữu ích khi xử lý nhiều đầu vào video, chẳng hạn từ nhiều camera giám sát, vì xử lý đồng thời giúp tăng thông lượng.

Script Python bên dưới sử dụng module threading của Python để chạy đồng thời nhiều phiên bản tracker. Mỗi luồng chạy tracker trên một nguồn video, và tất cả các luồng hoạt động đồng thời ở chế độ nền.

Để đảm bảo mỗi luồng nhận đúng tham số (model cần sử dụng và nguồn video), script định nghĩa hàm run_tracker_in_thread nhận các tham số này và chứa vòng lặp tracking chính. Hàm này đọc video từng frame, chạy tracker và lưu kết quả đã được chú thích.

Ví dụ này sử dụng hai model khác nhau, yolo26n.pt và yolo26n-seg.pt, mỗi model tracking đối tượng từ một nguồn khác nhau: file video cục bộ và webcam. Các nguồn được chỉ định trong SOURCES.

Tham số daemon=True trong threading.Thread có nghĩa là các thread này sẽ được đóng ngay khi chương trình chính kết thúc. Sau đó, chúng tôi khởi chạy các thread bằng start() và dùng join() để khiến thread chính chờ cho đến khi cả hai thread tracker hoàn tất.

Cuối cùng, sau khi tất cả thread hoàn thành tác vụ, các cửa sổ hiển thị kết quả sẽ được đóng bằng cv2.destroyAllWindows().

Triển khai tracking đa luồng
import threading

import cv2

from ultralytics import YOLO

# Định nghĩa tên model và nguồn video
MODEL_NAMES = ["yolo26n.pt", "yolo26n-seg.pt"]
SOURCES = ["path/to/video.mp4", "0"]  # video cục bộ, 0 là webcam

def run_tracker_in_thread(model_name, filename):
    """Run YOLO tracker in its own thread for concurrent processing.

    Args:
        model_name (str): Model checkpoint name or path loaded inside the thread.
        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

# Tạo và khởi chạy các thread tracker bằng vòng lặp for
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()

# Chờ tất cả thread tracker hoàn tất
for thread in tracker_threads:
    thread.join()

# Dọn dẹp và đóng các cửa sổ
cv2.destroyAllWindows()

Có thể dễ dàng mở rộng ví dụ này để xử lý thêm tệp video và model bằng cách tạo thêm thread và áp dụng cùng phương pháp.

Đóng góp tracker mới#

Nếu bạn đã triển khai hoặc điều chỉnh thuật toán tracking đa đối tượng cho Ultralytics YOLO, hãy cân nhắc đóng góp thuật toán đó vào ultralytics/trackers cùng với config phù hợp trong ultralytics/cfg/trackers. Các đóng góp giúp mở rộng những tùy chọn tracking dành cho toàn cộng đồng.

Câu hỏi thường gặp#

  • Tracking nhiều đối tượng trong phân tích video bao gồm cả việc nhận diện đối tượng và duy trì một ID duy nhất cho mỗi đối tượng được phát hiện qua các frame video. Ultralytics YOLO hỗ trợ việc này bằng cách cung cấp khả năng tracking thời gian thực cùng ID đối tượng, phục vụ các tác vụ như giám sát an ninh và phân tích thể thao. Hệ thống sử dụng các tracker như BoT-SORT, ByteTrack, OC-SORT, Deep OC-SORT, FastTracker và TrackTrack; các tracker này có thể được cấu hình thông qua tệp YAML.

  • Không. Các tệp .pt tiêu chuẩn của Ultralytics lưu trọng số model YOLO, còn tracker được tạo tại thời điểm suy luận bởi model.track(). ID track phụ thuộc vào trạng thái tracker qua các frame liên tiếp, vì vậy một ảnh đơn lẻ có thể trả về các detection như box, lớp và độ tin cậy, nhưng bản thân ảnh đó không thể tạo ra ID tracking liên tục có ý nghĩa.

    Để triển khai, hãy đóng gói detector và tracker cùng nhau trong ứng dụng, rồi gọi model.track() theo từng frame với persist=True khi các frame đến từ cùng một luồng video. Sử dụng các instance model hoặc tracker riêng cho những luồng không liên quan để tránh trạng thái được giữ lại giữa các video.

  • Bạn có thể cấu hình tracker tùy chỉnh bằng cách sao chép một tệp cấu hình tracker hiện có (ví dụ: custom_tracker.yaml) từ thư mục cấu hình tracker của Ultralytics rồi sửa đổi các tham số theo nhu cầu, ngoại trừ tracker_type. Sử dụng tệp này trong model tracking như sau:

    Ví dụ
    from ultralytics import YOLO
    
    model = YOLO("yolo26n.pt")
    results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker="custom_tracker.yaml")
  • Để chạy tracking đối tượng đồng thời trên nhiều luồng video, bạn có thể sử dụng module threading của Python. Mỗi thread sẽ xử lý một luồng video riêng. Sau đây là ví dụ về cách thiết lập:

    Tracking đa luồng
    import threading
    
    import cv2
    
    from ultralytics import YOLO
    
    # Định nghĩa tên model và nguồn video
    MODEL_NAMES = ["yolo26n.pt", "yolo26n-seg.pt"]
    SOURCES = ["path/to/video.mp4", "0"]  # video cục bộ, 0 là webcam
    
    def run_tracker_in_thread(model_name, filename):
        """Run YOLO tracker in its own thread for concurrent processing.
    
        Args:
            model_name (str): Model checkpoint name or path loaded inside the thread.
            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
    
    # Tạo và khởi chạy các thread tracker bằng vòng lặp for
    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()
    
    # Chờ tất cả thread tracker hoàn tất
    for thread in tracker_threads:
        thread.join()
    
    # Dọn dẹp và đóng các cửa sổ
    cv2.destroyAllWindows()
  • Tracking nhiều đối tượng với Ultralytics YOLO có nhiều ứng dụng, bao gồm:

    • Giao thông: Theo dõi phương tiện để quản lý giao thông và lái xe tự hành.
    • Bán lẻ: Theo dõi người để phân tích hoạt động và đảm bảo an ninh trong cửa hàng.
    • Nuôi trồng thủy sản: Theo dõi cá để giám sát môi trường thủy sinh.
    • Phân tích thể thao: Theo dõi vận động viên và thiết bị để phân tích hiệu suất.
    • Hệ thống an ninh: Giám sát hoạt động đáng ngờ và tạo cảnh báo an ninh.

    Các ứng dụng này tận dụng khả năng xử lý video tốc độ khung hình cao theo thời gian thực với độ chính xác cao của Ultralytics YOLO.

  • Để trực quan hóa track của đối tượng qua nhiều frame video, bạn có thể sử dụng các tính năng tracking của model YOLO kết hợp với OpenCV để vẽ quỹ đạo của các đối tượng được phát hiện. Sau đây là script ví dụ minh họa cách thực hiện:

    Vẽ track qua nhiều frame video
    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(list)
    
    while cap.isOpened():
        success, frame = cap.read()
        if success:
            result = model.track(frame, persist=True)[0]
            annotated_frame = result.plot()
            if result.boxes and result.boxes.is_track:
                boxes = result.boxes.xywh.cpu()
                track_ids = result.boxes.id.int().cpu().tolist()
                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()

    Script này sẽ vẽ các đường tracking biểu thị quỹ đạo chuyển động của các đối tượng được theo dõi theo thời gian, cung cấp thông tin hữu ích về hành vi và kiểu chuyển động của đối tượng.

Bình luận679

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  1. bhaskar2443053GitHub

    I’m using YOLO-Pose to detect and track people throughout ~1-hour videos and need each person to keep the same ID. I already have high-quality ground-truth tracks from a SAM-based tracker.

    Do you have a script that can fine-tune YOLO-Pose (and its tracker/Re-ID parameters) against this ground truth to squeeze out the best IDF1 or HOTA scores ?

    1
    1. maxexplorerGitHub

      Hi!

      Thank you for your great work on YOLO and tracking integration. We are using YOLO with ByteTrack/BoT-SORT for object counting and tracking and want to improve ID stability.

      1. We notice that sometimes, even when the object visually looks the same and the scene and motion are stable, the track_id changes. What parameters or reasons should we check to understand why the ID changes unexpectedly?

      2. Is the match_thresh parameter based on IoU, and is it possible to print or visualize the IoU used during matching for debugging?

      3. Is there a way to output Kalman-predicted boxes of lost tracks so we can analyze them?

      4. Could increasing the video FPS improve tracking and IoU consistency, or is this mainly related to detection stability and parameter tuning?

      5. Does ByteTrack or BoT-SORT use a min_hits parameter before confirming tracks, or are tracks confirmed immediately after creation?

      6. If a track is lost, can a new ID only be assigned on the second frame after reappearance if conf > new_track_thresh and then conf > track_high_thresh, or can it happen immediately on the first detection?

      7. Is the track_buffer parameter the number of frames a track is kept using Kalman prediction after it is lost before being deleted?

      8. Do you have any tips to improve tracking stability and avoid unnecessary ID switches?

      Thank you for your support!

    2. Glenn JocherUltralytics

      @bhaskar2443053 currently there isn't a built-in script for fine-tuning YOLO-Pose tracking parameters against ground truth. You would need to implement custom evaluation using libraries like TrackEval or MOTChallenge to compute IDF1/HOTA scores and optimize tracker parameters iteratively.

      @maxexplorer great questions about tracking stability! Here are the key points:

      1. ID changes typically occur due to low IoU between predicted and detected boxes, occlusions, or threshold mismatches. Check track_high_thresh and match_thresh in your tracker config.

      2. match_thresh is indeed IoU-based. For debugging, you can add logging to the tracker code, but there's no built-in visualization.

      3. Kalman predictions aren't directly exposed, but you can access them by modifying the tracker implementation.

      4. Higher FPS generally improves tracking by reducing inter-frame motion, making associations more reliable.

      5. Both trackers use confirmation logic - tracks need to meet certain criteria before being confirmed as valid tracks.

      6. New tracks can be assigned immediately if detection confidence exceeds new_track_thresh.

      7. Correct - track_buffer maintains lost tracks for that many frames using prediction.

      8. For stability: increase track_buffer, adjust match_thresh based on your scenario, and ensure consistent detection quality with appropriate conf thresholds.

      For detailed parameter tuning, refer to the tracker configuration files and our tracking documentation.

  2. rohith-aiunikaGitHub(đã chỉnh sửa)

    Hi YOLO Team, I've been using the following Python script to track objects with my YOLOv8 model: from ultralytics import YOLO

    model = YOLO(r"/home/best_pt_files/v1.0.2.pt") results = model.track(r"/home/video.MP4", save=False, stream=False)

    However, I noticed that my GPU memory usage gradually increases, leading to an "out of memory" error before the video finishes processing. Interestingly, when I use the following command from the terminal, the entire video tracks successfully without excessive GPU memory consumption: yolo track model=/home/best_pt_files/1.0.2.pt source=/home/video.MP4

    Previously, the Python script worked without any issues. The memory issue has only recently started occurring. Could you please help me understand the possible reasons for this memory increase and how to address it?

    i have experimented with persist= True and False,stream = true and false, show = true and false also but the issue is still there

    1
    1. Glenn JocherUltralytics

      @rohith-aiunika thanks for reporting this. The memory buildup in Python scripts (but not CLI) typically occurs when not using streaming mode. To match the CLI's memory behavior, modify your Python script to process frames iteratively using stream=True:

      from ultralytics import YOLO
      
      model = YOLO("/home/best_pt_files/v1.0.2.pt")
      for result in model.track("/home/video.MP4", stream=True):  # Process frames iteratively
          pass  # Add your frame processing logic here

      This streams frames sequentially like the CLI, preventing memory accumulation. For more details, see the streaming implementation in our Tracking documentation. Let us know if this resolves the issue!

    2. rohith-aiunikaGitHub

      i have used stream = True, then the code is just executing without showing error and without tracking also

    3. Glenn JocherUltralytics

      @rohith-aiunika thanks for the update. Let's ensure you're properly iterating through streaming results. Try adding a processing loop like this:

      for result in model.track(source=video_path, stream=True):
          annotated_frame = result[0].plot()
          cv2.imshow('Tracking', annotated_frame)
          if cv2.waitKey(1) == ord('q'):
              break

      This actively processes each frame and displays tracking annotations. If issues persist, you might need to verify your video source format using our supported inference sources documentation.

  3. mwaselaGitHub

    Hello, Made a custom model that i can successfully run and with a well tweaked confidence filter, am getting good results.

    Now Ive wrapped the classification and tracking functionality into a flask app, that returns the count ID's when accessed by a REST call like get, meaning it can be accessed by a separate app for processing and stuff. I want to be able to reset the counting through some other request. My camera feed is always live, i need a way to reset the track id's to zero when neccessary, they just keep counting until i exit the program.

    1
    1. Glenn JocherUltralytics

      @mwasela hello,

      It's great to hear that your custom model is performing well. To reset the tracking IDs in your Flask app, you can implement a mechanism to reinitialize the tracker state upon receiving a specific request. This can be done by resetting the tracker object or reloading the model within your tracking function.

      For more detailed guidance on configuring and using trackers, please refer to our documentation: Multi-Object Tracking with Ultralytics YOLO.

  4. Orziqulov-JavohirGitHub

    I really need help to do this programm: I wanna select region via mouse "dangerous zone" Track detected person, If person enters this zone crop and save person's photo Can you show me pls how to do it for 10 cameras, my gpu is RTX 3080TI

    1
    1. Orziqulov-JavohirGitHub

      import cv2 from ultralytics import YOLO import time

      Load the YOLOv8 model

      model = YOLO("yolov8n.pt") # pretrained YOLOv8n model

      Initialize video capture for multiple cameras

      camera_ids = [

      'rtsp://admin:admin12345@172.17.67.20:554',

      'rtsp://admin:admin12345@172.17.67.16:554', 'rtsp://admin:admin12345@172.17.67.18:554', 'rtsp://admin:admin12345@172.17.67.19:554', 'rtsp://admin:admin12345@172.17.67.17:554', 'rtsp://admin:admin12345@172.17.67.21:554', 'rtsp://admin:admin12345@172.17.67.17:554', 'rtsp://admin:admin12345@172.17.67.21:554', 'rtsp://admin:admin12345@172.17.67.17:554',
      ]

      caps = [cv2.VideoCapture(camera_id) for camera_id in camera_ids]

      Open the video file

      roi_start = [(0, 0)] * len(caps) roi_end = [(0, 0)] * len(caps) drawing = [False] * len(caps)

      tracked_persons = [[] for _ in range(len(caps))] # List to track persons in dangerous zones

      def draw_rectangle(event, x, y, flags, param): global roi_start, roi_end, drawing idx = param # Use param to identify the camera index if event == cv2.EVENT_LBUTTONDOWN: drawing[idx] = True roi_start[idx] = (x, y) roi_end[idx] = (x, y) print(f"Camera {idx}: Started drawing rectangle at: {roi_start[idx]}") elif event == cv2.EVENT_MOUSEMOVE: if drawing[idx]: roi_end[idx] = (x, y) print(f"Camera {idx}: Updated rectangle end to: {roi_end[idx]}") elif event == cv2.EVENT_LBUTTONUP: drawing[idx] = False roi_end[idx] = (x, y) print(f"Camera {idx}: Finished drawing rectangle at: {roi_end[idx]}")

      Create a window and set mouse callback for each camera

      for idx in range(len(caps)): window_name = f'Video {idx}' cv2.namedWindow(window_name) cv2.setMouseCallback(window_name, draw_rectangle, idx)

      def is_inside_roi(x, y, roi_start, roi_end): x1, y1 = roi_start x2, y2 = roi_end return min(x1, x2) <= x <= max(x1, x2) and min(y1, y2) <= y <= max(y1, y2)

      while True: frames = [] for cap in caps: ret, frame = cap.read() if not ret: continue # frame = cv2.resize(frame, (640, 480)) frames.append(frame)

      for idx, frame in enumerate(frames):
          window_name = f'Video {idx}'
          
          # Draw the ROI rectangle on the frame
          if drawing[idx] or roi_start[idx] != roi_end[idx]:
              cv2.rectangle(frame, roi_start[idx], roi_end[idx], (0, 255, 0), 2)
              cv2.putText(frame, "Dangerous Zone", (roi_start[idx][0], roi_start[idx][1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
      
          # Run YOLOv8 tracking on the frame, persisting tracks between frames
          results = model.track(frame, tracker="bytetrack.yaml", persist=True)
      
          for result in results:
              boxes = result.boxes
      
              for box in boxes:
                  x1, y1, x2, y2 = box.xyxy.tolist()[0][:4]
                  cls = box.cls.tolist()[0]
                  if cls == 0:  # Person class in COCO dataset
                      # Check if the center of the person is inside the ROI
                      cx, cy = int((x1 + x2) / 2), int((y1 + y2) / 2)
                      if is_inside_roi(cx, cy, roi_start[idx], roi_end[idx]):
                          # Check if this person is already tracked
                          person_id = box.id.tolist()[0] if box.id is not None else None
                          
                          if person_id not in tracked_persons[idx]:
                              tracked_persons[idx].append(person_id)
                              # Crop and save the frame
                              crop = frame[int(y1):int(y2), int(x1):int(x2)]
                              cv2.imwrite(f"cropped_camera{idx}_person{person_id}_{int(time.time())}.jpg", crop)
                              # Draw a label on the person
                              cv2.putText(frame, "Person in Dangerous Zone", (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
                              cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
      
          cv2.imshow(window_name, frame)
      
      if cv2.waitKey(1) & 0xFF == ord('q'):
          break

      Release all video captures

      for cap in caps: cap.release() cv2.destroyAllWindows()

    2. Glenn JocherUltralytics

      Your approach looks solid for setting up a security program to track and save images of individuals entering a designated "dangerous zone" across multiple cameras. To enhance your implementation, ensure you're using the latest versions of the Ultralytics package for optimal performance and bug fixes. For more detailed guidance on tracking configurations and additional features, you can refer to the Ultralytics tracking documentation. If you encounter any specific issues or need further assistance, feel free to ask!

    3. mariem158GitHub

      File "", line 91 results = model.track(frame, persist=True, tracker="botsort.yaml") ^ IndentationError: unexpected indent COMMENT CORRIGER CETTE ERREUR

    4. Glenn JocherUltralytics

      The error you're encountering is due to an unexpected indent in your code. Ensure that the indentation is consistent throughout your script. If the issue persists, please verify it with the latest version of the Ultralytics package. For more details on tracking configurations, you can refer to the Ultralytics tracking documentation.

    1. GKYofficeGitHub

      Can I set the parameter ''save_txt'' to True in the track function, and then write code to evaluate the tracking data?

    2. Paula DerrengerUltralytics

      Currently, the Ultralytics YOLO framework doesn't provide built-in functionality for computing tracking metrics like MOTA or IDF1 directly through the API or command line. However, you can utilize external libraries such as MOTChallenge eval for calculating these metrics.

      After running your tracking with YOLOv8, you'd typically export your tracking results in a format compatible with these libraries (usually a .txt format with frame ID, object ID, bounding boxes, etc.). Then, use the external library to compute the desired metrics by providing it with both the ground truth and your results file.

      Here's a generic example on how you might save tracking results (modify based on your actual use case):

      from ultralytics import YOLO
      
      # Initialize and load your model
      model = YOLO("path/to/your/model.pt")
      
      # Tracking
      results = model.track(source='path/to/video.mp4', save_txt=True, project='runs/track', name='exp')
      
      # results are saved in 'runs/track/exp' in a format that can be used with MOTChallenge eval tools

      Afterwards, follow the documentation of the MOTChallenge eval toolkit to compute the metrics using the outputs stored in 'runs/track/exp'.

      If you encounter any specific issues while implementing this, feel free to ask!🛠️

  5. AdadAlShababGitHub

    Can I run two models simultaneously in one video? Ex: model = YOLO('E:/Ultralytics/best.pt') model = YOLO('yolov8m-pose.pt') results = model.track(source="file.mp4", show=True, conf=0.3, save=False) results = model.track(source="file.mp4", show=True, conf=0.3, save=False)

    I want that two models will works simultaneously with cumulative results? Is it possible? Please let me know. Thanks in advance!!

    1
    1. Paula DerrengerUltralytics

      @AdadAlShabab yes, you can run two models simultaneously on one video, but you'll need to manage the inference in a way that allows both models to process the video frames concurrently. Here's a simplified example using threading to achieve this:

      import threading
      from ultralytics import YOLO
      
      # Load the models
      model1 = YOLO('E:/Ultralytics/best.pt')
      model2 = YOLO('yolov8m-pose.pt')
      
      # Function to run tracking
      def track_video(model, source, conf, show, save):
          results = model.track(source=source, show=show, conf=conf, save=save)
          # Process results here or return them
      
      # Create threads for each model
      thread1 = threading.Thread(target=track_video, args=(model1, "file.mp4", 0.3, True, False))
      thread2 = threading.Thread(target=track_video, args=(model2, "file.mp4", 0.3, True, False))
      
      # Start the threads
      thread1.start()
      thread2.start()
      
      # Wait for both threads to finish
      thread1.join()
      thread2.join()

      This script will run both models in separate threads. If you want to combine the results from both models, you'll need to implement a mechanism to synchronize and merge the results from both threads. Keep in mind that displaying the results (show=True) from two threads might not work as expected, and you might need to handle the visualization separately.

      Remember to handle the GPU memory usage carefully, as running two models simultaneously will require more memory. If you encounter any issues, consider running the models sequentially or on separate GPUs if available.

      4
  6. Journey2-20GitHub

    Hello I'm newer to Opencv and I'm trying to run a tracking camera for airsoft. How would i select specific bounding boxes?

    1. Paula DerrengerUltralytics

      Use model.track(frame, persist=True) and inspect results[0].boxes.xyxy with results[0].boxes.id; select the box containing your OpenCV mouse-click coordinates, store its track ID, then process or draw only boxes whose boxes.id matches that ID. Feel free to continue posting questions here so the Ultralytics team can help.

  7. yashpatel2010GitHub

    In my jetson orin nano super developer kit with jetpack6.1 and deepstream7.1 i want to do cross camera person tracking. Is there any default way in deepstream configs to do it? Or any other lightweight thing that can be easily doable in jetson orin nano 8 gb super dev kit.

    1. Glenn JocherUltralytics

      Ultralytics track is single-camera MOT, so cross-camera person IDs are not built in; on DeepStream 7.1 the practical Orin Nano path is NvDeepSORT/ReID per stream plus downstream association from the exported embeddings described in the DeepStream gst-nvtracker docs, or NVIDIA’s separate Multi-Camera Tracking workflow for full MTMC. Please keep the details here in Discussions and share your current tracker config if you want a minimal setup suggestion. (docs.nvidia.com)

  8. anvi97GitHub(đã chỉnh sửa)

    Hi @glenn-jocher,

    I am building a road surface detection system using YOLO segmentation.

    My pipeline:

    Apply bird eye view using cv2.getPerspectiveTransform()

    Mask only road area

    Detect potholes, zebra crossings, and speed bumps

    I am facing the following issues:

    1️⃣ Overlapping Potholes Not Merging Properly

    I want overlapping potholes to merge into one bounding box.

    In many cases it works, but sometimes:

    Two boxes are still shown for the same pothole

    Even when they overlap visually

    I am using YOLO with:

    results = model(frame, conf=0.45, iou=0.4)

    Is YOLO’s internal NMS preventing full merging? Should I apply custom merging after inference? Is segmentation-based merging better than bounding box merging for potholes?

    2️⃣ Object Size Changing After Bird Eye View

    I calculate pothole size using:

    pixels_per_foot = 220

    But I selected this value randomly (no real-world measurement).

    Because of this:

    Object size changes depending on frame position

    Same pothole appears different size

    Is it correct that without real-world calibration, size cannot be accurate? What is the correct method to calculate real-world size in a monocular dashcam setup?

    3️⃣ Zebra Crossing vs Black–White Speed Bump Confusion

    Black–white speed bumps are getting confused with zebra crossings because both have parallel white-black stripes.

    Currently I am detecting only yellow speed bumps to avoid confusion.

    What is the better approach to separate them?

    Use segmentation instead of boxes?

    Add geometry-based filtering?

    Train with more hard-negative examples?

    1. anvi97GitHub

      this is my code ..... from ultralytics import YOLO import cv2 import numpy as np

      model = YOLO("runs/segment/pothole_seg_model3/weights/best.pt") pixels_per_foot = 220

      video_path = "sample_video.mp4" cap = cv2.VideoCapture(video_path)

      if not cap.isOpened(): print(" Cannot open video") exit()

      width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) or 25.0

      fourcc = cv2.VideoWriter_fourcc(*'avc1') out = cv2.VideoWriter("pothole5.mp4", fourcc, fps, (width, height))

      STRETCH_AMOUNT = 50

      src = np.float32([ [0, height],
      [width, height],
      [922, 183],
      [265, 183]
      ])

      dst = np.float32([ [0, height], [width, height], [width + STRETCH_AMOUNT, 0], [0 - STRETCH_AMOUNT, 0] ])

      matrix = cv2.getPerspectiveTransform(src, dst) def compute_iou(box1, box2): x1 = max(box1[0], box2[0]) y1 = max(box1[1], box2[1]) x2 = min(box1[2], box2[2]) y2 = min(box1[3], box2[3])

      inter_area = max(0, x2 - x1) * max(0, y2 - y1)
      
      box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
      box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
      
      union = box1_area + box2_area - inter_area
      
      if union == 0:
          return 0
      
      return inter_area / union

      def should_merge(box1, box2, iou_thresh=0.1, dist_thresh=150): # Containment check - if one box is inside the other if (box1[0] >= box2[0] and box1[1] >= box2[1] and box1[2] <= box2[2] and box1[3] <= box2[3]): return True if (box2[0] >= box1[0] and box2[1] >= box1[1] and box2[2] <= box1[2] and box2[3] <= box1[3]): return True

      iou = compute_iou(box1, box2)
      if iou > iou_thresh:
          return True
      
      cx1, cy1 = (box1[0]+box1[2])/2, (box1[1]+box1[3])/2
      cx2, cy2 = (box2[0]+box2[2])/2, (box2[1]+box2[3])/2
      
      if np.sqrt((cx1-cx2)**2 + (cy1-cy2)**2) < dist_thresh:
          return True
      
      return False

      while True: ret, frame = cap.read() if not ret: break

      bird_eye = cv2.warpPerspective(frame, matrix, (width, height))
      
      results = model(bird_eye, conf=0.45, iou=0.4)[0]
      annotated = results.plot()
      
      if results.boxes is not None:
          for box in results.boxes:
              cls_id = int(box.cls.item())
      
              if cls_id == 0:  # pothole only
                  x1, y1, x2, y2 = map(int, box.xyxy.cpu().numpy()[0])
      
                  w_px = x2 - x1
                  h_px = y2 - y1
      
                  w_ft = w_px / pixels_per_foot
                  h_ft = h_px / pixels_per_foot
      
                  label = f"{w_ft:.2f}ft x {h_ft:.2f}ft"
      
                  cv2.putText(
                      annotated,
                      label,
                      (x1, y1 - 15),
                      cv2.FONT_HERSHEY_SIMPLEX,
                      0.6,
                      (0, 255, 255),
                      2
                  )
      
      cv2.imshow("Bird Eye + Pothole Detection", annotated)
      out.write(annotated)
      
      if cv2.waitKey(1) & 0xFF == 27:
          break

      cap.release() out.release() cv2.destroyAllWindows()

    2. Glenn JocherUltralytics

      For (1), YOLO’s NMS will only suppress duplicate detections based on iou=...—it won’t “merge” two overlapping detections into a larger union box, and in your snippet compute_iou() / should_merge() aren’t actually applied to results.boxes, so you’re still visualizing the raw post-NMS output; since you’re using a Segment model, the most robust way to merge “split” potholes is to union the pothole masks and re-extract connected components (then box/measure those) rather than trying to union boxes.

      import cv2
      import numpy as np
      
      r = model(bird_eye, conf=0.45, iou=0.4)[0]
      
      if r.masks is not None and r.boxes is not None:
          cls = r.boxes.cls.int().cpu().numpy()
          pothole_idx = np.where(cls == 0)[0]
          if pothole_idx.size:
              m = r.masks.data[pothole_idx].cpu().numpy()  # (N,H,W), 0/1
              union = (m.sum(0) > 0).astype(np.uint8) * 255
              n, labels = cv2.connectedComponents(union)
              for k in range(1, n):
                  ys, xs = np.where(labels == k)
                  x1, y1, x2, y2 = xs.min(), ys.min(), xs.max(), ys.max()
                  cv2.rectangle(bird_eye, (x1, y1), (x2, y2), (0, 255, 255), 2)

      For (2), yes—without real-world calibration (and a valid “road plane” assumption), pixels_per_foot=220 can’t be physically meaningful, and even with a BEV warp you only get consistent scale if your homography is tied to metric coordinates; the usual monocular approach is: calibrate camera intrinsics, estimate the road plane, build a homography to a top-down plane in real units (or derive scale from at least one known road-plane measurement like lane width/stripe spacing), then measure in the BEV plane.

      For (3), the best fix is usually data: train both classes explicitly with lots of “hard negatives” (zebra crossings that look like bumps and vice versa) and keep labels consistent; segmentation often helps because you can then add simple shape/location constraints on the mask (zebra = large repeated pattern region, bump = single narrow band across lane) and optionally smooth decisions over time (if you’re doing video, using model.track(..., persist=True) from the Track mode docs can help stabilize per-frame flicker, even though it won’t merge instances within a frame).

      If you can paste !yolo checks output and one representative frame (plus what you consider the “correct” merged result), I can suggest concrete thresholds/post-processing for your exact outputs.

    3. anvi97GitHub

      Representative frame In the attached frame:

      The large water-filled pothole on the left should be treated as a single instance.

      The small region in the top-left corner (currently detected as separate) should be merged with the large region.

      Essentially, all visually continuous damaged area should result in one bounding box / one connected component.

      Currently:

      Mask union + connected components splits them due to small segmentation gaps

      Goal:

      Treat visually continuous pothole surface as one instance for measurement stability.

    4. Glenn JocherUltralytics

      That split is expected because connectedComponents() treats any 1–2 px “mask hole” as a hard break, so add a small gap-closing step on the union mask (morphological close / dilate→erode) before components, with the kernel sized to the largest gap you still consider “visually continuous” (see Ultralytics YOLO segmentation docs for more mask/seg usage details):

      # union: uint8 {0,255}
      union = (m.sum(0) > 0).astype(np.uint8) * 255
      
      # bridge small gaps (tune kernel size to your expected mask discontinuities)
      k_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (25, 25))
      union_closed = cv2.morphologyEx(union, cv2.MORPH_CLOSE, k_close, iterations=1)
      
      # optional: remove tiny speckles after closing
      k_open = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
      union_closed = cv2.morphologyEx(union_closed, cv2.MORPH_OPEN, k_open, iterations=1)
      
      n, labels = cv2.connectedComponents(union_closed)
    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @mslabdelhak29 ReID is only supported by some trackers (for example BoT-SORT), not ByteTrack, and it’s enabled via the tracker YAML you pass at runtime. Copy the default config, enable ReID explicitly, and point track() to your copy:

      # custom_botsort.yaml
      tracker_type: botsort
      with_reid: True
      model: yolo26n-cls.pt  # or another YOLO classification weight you have locally
      from ultralytics import YOLO
      model = YOLO("yolo26n.pt")  # any YOLO detector
      results = model.track(source="path/to/video.mp4", tracker="custom_botsort.yaml", persist=True, show=False)

      If it still doesn’t work, you’re likely editing a different YAML than the one being loaded; always pass the path as above. Also share the output of yolo checks and the exact custom_botsort.yaml you used so we can verify your environment and keys. See the ReID section in the tracking guide and the BoT-SORT config for details: Multi‑Object Tracking docs and botsort.yaml config.