To replace DeepSort with the existing YOLO model for object tracking, you'll need to modify the ObjectTracker class to leverage YOLO's built-in tracking capabilities. Ultralytics' YOLOv8 supports various tracking algorithms (like ByteTrack) that can be integrated directly, eliminating the need for DeepSort.
Below are the detailed steps and code modifications required to achieve this transformation:
-
Remove DeepSort Dependencies:
- Eliminate the import of DeepSort from the
ObjectTracker class.
- Remove any DeepSort-specific initialization and usage.
-
Integrate YOLO's Built-in Tracking:
- Utilize YOLO's tracking features by enabling tracking during the detection phase.
- Process tracking IDs provided by YOLO and manage them within your application.
-
Update ObjectTracker Class:
- Modify the
ObjectTracker class to handle tracking using YOLO's outputs.
- Update methods to process track IDs instead of relying on DeepSort.
-
Adjust the ObjectDetection Class (if necessary):
- Ensure that the
ObjectDetection class is set up to support tracking by configuring the YOLO model accordingly.
-
Update the Main Function:
- Ensure that the main processing loop correctly handles tracked objects with their unique IDs.
Below are the revised code snippets reflecting these changes:
1. Updated ObjectDetection Class
Ensure that the ObjectDetection class is configured to support tracking. YOLOv8 can perform tracking by specifying the tracker type when calling the track method.
# ObjectDetection.py
from ultralytics import YOLO
import os
class ObjectDetection:
"""
A class for object detection using a YOLO model.
Attributes:
model (YOLO): The YOLO model used for detection and tracking.
classNames (list): List of class names that the model can detect.
allowed_classes (set): Set of class indices that are allowed for tracking.
"""
def __init__(self, model="yolov8n.pt"):
"""
Initializes the ObjectDetection class with the specified YOLO model.
Args:
model (str): The path to the YOLO model weights.
"""
try:
self.model = YOLO(model) # Load YOLO model
except Exception as e:
raise Exception(f"Error loading YOLO model: {e}")
self.classNames = ["person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", "boat",
"traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat",
"dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella",
"handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat",
"baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup",
"fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli",
"carrot", "hot dog", "pizza", "donut", "cake", "chair", "sofa", "pottedplant", "bed",
"diningtable", "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", "cell phone",
"microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors",
"teddy bear", "hair drier", "toothbrush"]
# Only allow certain classes for tracking
self.allowed_classes = {0, 24, 25, 26, 31, 36, 37, 39, 40, 41, 53, 63, 65, 67}
def detect_and_track_objects(self, img):
"""
Detects and tracks objects in the given image using YOLO's tracking capabilities.
Args:
img (numpy.ndarray): The image in which to detect and track objects.
Returns:
list: A list of detections, each containing class name, bounding box coordinates, width, height, confidence, and track ID.
"""
# Enable tracking by specifying the tracker type (e.g., 'bytetrack.yaml')
results = self.model.track(source=img, tracker='bytetrack.yaml', persist=True)
detections = []
for result in results:
for track in result.track:
cls = int(track.cls.cpu().numpy())
if cls not in self.allowed_classes:
continue # Skip classes that are not allowed
class_name = self.classNames[cls]
x1, y1, x2, y2 = map(int, track.xyxy.cpu().numpy())
width, height = x2 - x1, y2 - y1
confidence = track.conf.cpu().numpy()
track_id = track.track_id.cpu().numpy()
detections.append((class_name, x1, y1, width, height, confidence, track_id))
return detections
Key Changes:
- Tracking Enabled: The
detect_and_track_objects method now uses self.model.track instead of self.model(img), enabling tracking via YOLO's ByteTrack by specifying the tracker configuration file.
- Track ID Retrieval: Each detection now includes a
track_id provided by YOLO, which uniquely identifies each tracked object across frames.
2. Updated ObjectTracker Class
Modify the ObjectTracker to leverage the tracking information provided by YOLO.
# ObjectTracker.py
import cv2
from datetime import datetime, timedelta
from Status import Status
from insightface.app import FaceAnalysis
import numpy as np
import math
class ObjectTracker:
"""
A class for tracking objects using YOLO's built-in tracker and updating their status in the database.
Attributes:
db (Database): The database instance for storing object data.
detection_model (ObjectDetection): The object detection model with tracking capabilities.
object_positions (dict): Dictionary to store the positions of each object.
"""
def __init__(self, db, detection_model):
"""
Initializes the ObjectTracker class with the given database and detection model.
Args:
db (Database): The database instance.
detection_model (ObjectDetection): The object detection model with tracking.
"""
self.db = db
self.detection_model = detection_model
self.object_positions = {} # To store positions of each object
# Initialize ArcFace for face recognition
self.face_recognizer = FaceAnalysis(allowed_modules=['detection', 'recognition'])
self.face_recognizer.prepare(ctx_id=0, det_size=(320, 320))
self.face_recognition_cache = {} # Stores obj_id: (person_name, last_recognition_frame)
self.face_recognition_interval = 10 # Number of frames to wait before re-running face recognition
self.frame_count = 0 # Initialize frame counter
def is_near(self, existing_obj, new_obj, size_similarity_threshold=0.2, location_similarity_threshold=30):
"""
Determines if a new object is similar to an existing object based on size and location.
Args:
existing_obj (tuple): The existing object's coordinates and size (x, y, w, h).
new_obj (tuple): The new object's coordinates and size (x, y, w, h).
size_similarity_threshold (float, optional): Maximum relative difference in size to consider similar
(default is 0.2 for 20%).
location_similarity_threshold (int, optional): Maximum distance between centers to consider similar
(default is 30 pixels).
Returns:
bool: True if the objects are similar in size and location, False otherwise.
"""
ex, ey, ew, eh = existing_obj
nx, ny, nw, nh = new_obj
# Calculate centers of existing and new objects
existing_center_x = ex + ew / 2
existing_center_y = ey + eh / 2
new_center_x = nx + nw / 2
new_center_y = ny + nh / 2
# Calculate Euclidean distance between centers
center_distance = math.sqrt((existing_center_x - new_center_x) ** 2 + (existing_center_y - new_center_y) ** 2)
# Check location similarity
if center_distance > location_similarity_threshold:
return False # Objects are too far apart in location
# Calculate relative size differences
width_difference = abs(ew - nw) / max(ew, nw)
height_difference = abs(eh - nh) / max(eh, nh)
# Check size similarity
if width_difference > size_similarity_threshold or height_difference > size_similarity_threshold:
return False # Objects differ too much in size
return True # Objects are similar in both size and location
def is_within_frame(self, obj_id, frame_width, frame_height, border_threshold=20, size_threshold=60):
"""
Checks if an object is within the frame or near the borders. If the object is near a border and its size is
small (less than size_threshold), it is considered out of bounds.
Args:
obj_id (int): The ID of the object.
frame_width (int): The width of the frame.
frame_height (int): The height of the frame.
border_threshold (int, optional): The distance from borders to consider as 'near the border'.
size_threshold (int, optional): The size threshold to consider the object as out of bounds if near border.
Returns:
bool: True if the object is within the frame, False if it's out of bounds.
"""
positions = self.object_positions.get(obj_id, [])
if not positions:
return False # No position data available
x, y, w, h = positions[-1] # Get the most recent position
# Check distances from borders
distance_left = x
distance_right = frame_width - (x + w)
distance_top = y
distance_bottom = frame_height - (y + h)
# If object is near left border
if distance_left <= border_threshold and w <= size_threshold:
return False # Object is out of bounds
# If object is near right border
if distance_right <= border_threshold and w <= size_threshold:
return False
# If object is near top border
if distance_top <= border_threshold and h <= size_threshold:
return False
# If object is near bottom border
if distance_bottom <= border_threshold and h <= size_threshold:
return False
# If none of the above conditions met, object is within frame
return True
def check_for_false_positives(self, frame_width, frame_height):
"""
Checks the database for objects that haven't been seen for more than 500 ms.
If an object hasn't been seen for more than 500 ms and is not within frame,
updates its status to 'Left Frame'. If detection_count < 5, deletes it.
Args:
frame_width (int): The width of the frame.
frame_height (int): The height of the frame.
"""
all_objects = self.db.fetch_all_objects()
now = datetime.now()
detection_timeout = now - timedelta(milliseconds=500)
for obj in all_objects:
obj_id = obj[0]
class_name = obj[1]
x1 = obj[2]
y1 = obj[3]
width = obj[4]
height = obj[5]
last_seen_str = obj[6]
status = obj[7]
detection_count = obj[8]
last_seen = datetime.fromisoformat(last_seen_str)
# If the object hasn't been seen for more than 500 ms
if last_seen < detection_timeout:
if detection_count < 6:
# Delete the object from the database
self.db.delete_object(obj_id)
# Remove from position tracking
if obj_id in self.object_positions:
del self.object_positions[obj_id]
else:
# Check if the object is within the frame
if not self.is_within_frame(obj_id, frame_width, frame_height):
# Update the object's status to 'Left Frame'
self.db.update_status(obj_id, Status.LEFT_FRAME)
def track_objects(self, img):
"""
Tracks objects in the given image, updates their status in the database, and annotates the image.
Args:
img (numpy.ndarray): The current video frame.
Returns:
numpy.ndarray: The annotated image.
"""
self.frame_count += 1 # Update frame count
frame_height, frame_width = img.shape[:2]
detections = self.detection_model.detect_and_track_objects(img)
formatted_detections = []
for detection in detections:
class_name, x1, y1, width, height, confidence, track_id = detection
formatted_detections.append(([x1, y1, width, height], confidence, class_name, track_id))
cv2.rectangle(img, (x1, y1), (x1 + width, y1 + height), (255, 0, 255), 2)
cv2.putText(img, f'{class_name} {confidence:.2f} ID:{track_id}', (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)
person_name = None # Initialize person_name
if class_name not in self.detection_model.classNames:
continue # Skip if class name is not recognized
# Update or insert object in the database based on track_id
obj_id = track_id # Use track_id as obj_id for consistency
existing_obj = self.db.fetch_object_by_id(obj_id)
if existing_obj:
# Update existing object
self.db.update_object(obj_id, x1, y1, width, height)
else:
# Insert new object
obj_id = self.db.insert_object(class_name, x1, y1, width, height)
self.db.update_status(obj_id, Status.IN_FRAME)
self.object_positions[obj_id] = [(x1, y1, width, height)]
# Perform face recognition for 'person' class
if class_name == 'person':
last_recognition = self.face_recognition_cache.get(obj_id, (None, -self.face_recognition_interval))[1]
if self.frame_count - last_recognition >= self.face_recognition_interval:
person_name = self.perform_face_recognition(img, x1, y1, width, height)
if person_name:
self.face_recognition_cache[obj_id] = (person_name, self.frame_count)
else:
person_name = self.face_recognition_cache.get(obj_id, (None, None))[0]
if person_name and person_name != 'Unknown' and person_name != 'No Face Detected':
self.db.update_known_face_object_link(obj_id, person_name)
cv2.putText(img, f'Name: {person_name} - ID:{obj_id}', (x1, y1 - 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
self.check_for_false_positives(frame_width, frame_height)
return img
def perform_face_recognition(self, img, x1, y1, width, height):
"""
Performs face recognition on the detected person.
Args:
img (numpy.ndarray): The current video frame.
x1 (int): The x-coordinate of the bounding box's top-left corner.
y1 (int): The y-coordinate of the bounding box's top-left corner.
width (int): The width of the bounding box.
height (int): The height of the bounding box.
Returns:
str: The recognized person's name or 'Unknown'/'No Face Detected'.
"""
person_img = img[y1:y1+height, x1:x1+width]
faces = self.face_recognizer.get(person_img)
if faces:
face = faces[0]
face_embedding = face.embedding / np.linalg.norm(face.embedding)
known_faces = self.db.fetch_known_faces()
min_distance = float('inf')
matched_name = None
for known_face in known_faces:
known_name = known_face[0]
known_embedding = known_face[1] / np.linalg.norm(known_face[1])
distance = np.linalg.norm(face_embedding - known_embedding)
if distance < min_distance:
min_distance = distance
matched_name = known_name
threshold = 1.0 # Adjust based on your model and data
if min_distance < threshold:
return matched_name
else:
return 'Unknown'
else:
return 'No Face Detected'
Key Changes:
- Removed DeepSort: All dependencies and initializations related to DeepSort have been removed.
- Leveraged YOLO Tracking IDs: The
track_id provided by YOLO is used as obj_id, ensuring consistency across frames.
- Simplified Tracking Logic: The tracking logic now relies on YOLO's tracking capabilities, which manage object IDs and trajectories.
- Face Recognition Integration: Maintains face recognition functionality, updating the database with recognized person names based on tracked IDs.
3. Updated main Function
Ensure that the ObjectTracker is correctly initialized and that frames are processed using the updated tracking mechanism.
# main.py
from Database import Database
from ObjectDetection import ObjectDetection
from ObjectTracker import ObjectTracker
from FaceInterface import FaceInterface
import cv2
import argparse
import time
def add_known_faces(file_path: str, face_interface: FaceInterface) -> None:
"""
Add known faces from the CSV file to the face recognition module.
Args:
file_path (str): Path to the CSV file containing image paths and names.
face_interface (FaceInterface): The face recognition interface.
Raises:
ValueError: If a known face could not be added.
"""
if file_path:
with open(file_path, 'r') as file:
for line in file:
image_path, name = line.strip().split(',')
if not face_interface.add_known_face(image_path, name):
raise ValueError(f"Failed to add {name} from {image_path}")
def main():
"""
The main function to initialize object detection and tracking,
and process the video stream from the webcam.
"""
# Set up argument parser
parser = argparse.ArgumentParser(description="CSV file of image_path, name. For face recognition.")
parser.add_argument('--csv', type=str, help='Path to the CSV file for face recognition.')
parser.add_argument('--model', type=str, default='yolov8n.pt', help='The YOLO model weights name. Default is yolov8n.pt.')
parser.add_argument('--show', action='store_true', help='Display the video stream.')
parser.add_argument('--fps', action='store_true', help='Whether to display the FPS.')
args = parser.parse_args()
# Initialize the database, detection model, and tracker
db = Database()
detection_model = ObjectDetection(model=args.model)
tracker = ObjectTracker(db, detection_model)
face_interface = FaceInterface(db)
# Add known faces from the CSV file
add_known_faces(args.csv, face_interface)
# Set up video capture from the default webcam
cap = cv2.VideoCapture(0)
cap.set(3, 640) # Set width
cap.set(4, 480) # Set height
# Initialize FPS calculation variables
frame_count = 0
start_time = time.time()
while True:
success, img = cap.read()
if not success:
break
# Perform object tracking on the current frame
img = tracker.track_objects(img)
if args.fps:
# Increment frame count
frame_count += 1
# Calculate FPS
elapsed_time = time.time() - start_time
fps = frame_count / elapsed_time
# Show the FPS on the frame
cv2.putText(img, f'FPS: {fps:.2f}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
if args.show:
cv2.imshow('Webcam', img)
# Exit if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release resources
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
Key Changes:
- No Change Needed: The
main function doesn't require significant changes as the tracking logic is now encapsulated within the updated ObjectTracker and ObjectDetection classes.
4. Updated Database Class
Ensure that the tracked_objects table includes a track_id column to store YOLO's tracking IDs.
# Database.py (Only the insert_object and create_table methods need updates)
import sqlite3
import datetime
from Status import Status
import numpy as np
class Database:
# ... [Other methods remain unchanged]
def create_table(self):
"""
Creates the 'tracked_objects' table if it does not already exist.
"""
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS tracked_objects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
track_id INTEGER UNIQUE, -- Added track_id to uniquely identify tracked objects
class_name TEXT,
x1 INTEGER,
y1 INTEGER,
width INTEGER,
height INTEGER,
last_seen DATETIME,
status TEXT,
detection_count INTEGER DEFAULT 0
)
''')
self.conn.commit()
def insert_object(self, class_name, x1, y1, width, height, track_id=None, person_name=None):
"""
Inserts a new object into the database, and returns the new object's ID.
Args:
class_name (str): The class name of the object.
x1 (int): The x-coordinate of the object's top-left corner.
y1 (int): The y-coordinate of the object's top-left corner.
width (int): The width of the object.
height (int): The height of the object.
track_id (int, optional): The tracking ID assigned by YOLO.
person_name (str, optional): The name of the person associated with the object.
Returns:
int: The ID of the newly inserted object.
"""
last_seen = datetime.datetime.now().isoformat()
status = Status.IN_FRAME.value
detection_count = 1
self.cursor.execute('''
INSERT OR IGNORE INTO tracked_objects (track_id, class_name, x1, y1, width, height, last_seen, status, detection_count, person_name)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (track_id, class_name, x1, y1, width, height, last_seen, status, detection_count, person_name))
self.conn.commit()
# Retrieve the object ID based on track_id
self.cursor.execute('SELECT id FROM tracked_objects WHERE track_id=?', (track_id,))
row = self.cursor.fetchone()
return row[0] if row else None
def update_object(self, obj_id, x1, y1, width, height):
"""
Updates the position and size of an existing object in the database, and increments detection_count.
Args:
obj_id (int): The ID of the object to update.
x1 (int): The new x-coordinate of the object's top-left corner.
y1 (int): The new y-coordinate of the object's top-left corner.
width (int): The new width of the object.
height (int): The new height of the object.
Returns:
int: The ID of the updated object.
"""
last_seen = datetime.datetime.now().isoformat()
status = Status.IN_FRAME.value # Set status to 'In Frame'
self.cursor.execute('''
UPDATE tracked_objects
SET x1=?, y1=?, width=?, height=?, last_seen=?, status=?, detection_count=detection_count+1
WHERE id=?
''', (x1, y1, width, height, last_seen, status, obj_id))
self.conn.commit()
return obj_id
Key Changes:
- Added
track_id: The tracked_objects table now includes a track_id column, which is unique and corresponds to YOLO's tracking ID.
- Modified
insert_object Method: Now accepts track_id and ensures that each tracked object is uniquely identified by its track_id.
- Updated
update_object Method: Remains largely unchanged but ensures consistency with the new table structure.
5. Ensure the known_face_object_link Table References track_id if Necessary
If your application logic requires linking known faces to specific tracked IDs, ensure that foreign keys and relationships in the known_face_object_link table are correctly referencing the track_id.
# Database.py (create_known_face_object_link_table method)
def create_known_face_object_link_table(self):
"""
Creates the 'known_face_object_link' table if it does not already exist.
"""
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS known_face_object_link (
known_face_name TEXT,
track_id INTEGER,
FOREIGN KEY (known_face_name) REFERENCES known_faces(name),
FOREIGN KEY (track_id) REFERENCES tracked_objects(track_id),
PRIMARY KEY (known_face_name, track_id)
)
''')
self.conn.commit()
Key Changes:
- Adjusted Foreign Key: Changed
object_id to track_id to accurately reference the tracking ID from YOLO.
6. Final Considerations
-
Tracker Configuration File: Ensure that the bytetrack.yaml file (or any other tracker configuration you prefer) is correctly placed and accessible by the YOLO model. You can customize tracking parameters within this file as needed.
-
Unique Track IDs: YOLO's built-in tracker assigns unique track_ids to each detected object. These IDs persist across frames, enabling consistent tracking without the need for an external tracker like DeepSort.
-
Performance Optimization: Depending on your use case and hardware, you may need to adjust YOLO's model size (e.g., using yolov8s.pt for faster performance) or tweak tracker parameters to balance accuracy and speed.
-
Error Handling: Incorporate additional error handling as needed, especially around face recognition and database operations, to ensure robustness.
By following these modifications, your application will utilize YOLO's built-in tracking capabilities, simplifying the tracking pipeline and eliminating the dependency on DeepSort. This integration leverages YOLO's efficient detection and tracking, providing a streamlined and cohesive object tracking solution.