For this code: `import sqlite3
import datetime
from Status import Status
class Database:
"""
A class to handle interactions with the SQLite database for object tracking.
Attributes:
conn (sqlite3.Connection): The database connection.
cursor (sqlite3.Cursor): The database cursor.
"""
def __init__(self, db_path='object_tracking.db'):
"""
Initializes the Database class with a connection to the specified SQLite database.
Args:
db_path (str): The path to the SQLite database file.
"""
self.conn = sqlite3.connect(db_path)
self.cursor = self.conn.cursor()
self.create_table()
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,
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 fetch_objects(self, class_name=None):
"""
Fetches objects from the database, optionally filtered by class name.
Args:
class_name (str, optional): The class name to filter objects.
Returns:
list: A list of tuples representing the objects.
"""
if class_name:
self.cursor.execute('SELECT * FROM tracked_objects WHERE class_name=?', (class_name,))
else:
self.cursor.execute('SELECT * FROM tracked_objects')
return self.cursor.fetchall()
def fetch_all_objects(self):
"""
Fetches all objects from the database.
Returns:
list: A list of tuples representing all objects.
"""
self.cursor.execute('SELECT * FROM tracked_objects')
return self.cursor.fetchall()
def fetch_object_by_id(self, obj_id):
"""
Fetches a single object by its ID.
Args:
obj_id (int): The ID of the object.
Returns:
tuple: The object data as a tuple.
"""
self.cursor.execute('SELECT * FROM tracked_objects WHERE id=?', (obj_id,))
return self.cursor.fetchone()
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
def insert_object(self, class_name, x1, y1, width, height):
"""
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.
Returns:
int: The ID of the newly inserted object.
"""
last_seen = datetime.datetime.now().isoformat()
status = Status.IN_FRAME.value # Set status to 'In Frame'
detection_count = 1
self.cursor.execute('''
INSERT INTO tracked_objects (class_name, x1, y1, width, height, last_seen, status, detection_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (class_name, x1, y1, width, height, last_seen, status, detection_count))
self.conn.commit()
return self.cursor.lastrowid
def update_status(self, obj_id, status):
"""
Updates the status of an object in the database.
Args:
obj_id (int): The ID of the object to update.
status (Status): The new status of the object.
"""
self.cursor.execute('''
UPDATE tracked_objects
SET status=?
WHERE id=?
''', (status.value, obj_id))
self.conn.commit()
def delete_object(self, obj_id):
"""
Deletes an object from the database.
Args:
obj_id (int): The ID of the object to delete.
"""
self.cursor.execute('''
DELETE FROM tracked_objects WHERE id=?
''', (obj_id,))
self.conn.commit()`, `# Import necessary libraries
Assistant
from Database import Database
from ObjectDetection import ObjectDetection
from ObjectTracker import ObjectTracker
import cv2
def main():
"""
The main function to initialize object detection and tracking,
and process the video stream from the webcam.
"""
# Initialize the database, detection model, and tracker
db = Database()
detection_model = ObjectDetection()
tracker = ObjectTracker(db, detection_model)
# Set up video capture from the default webcam
cap = cv2.VideoCapture(0)
cap.set(3, 640) # Set width
cap.set(4, 480) # Set height
while True:
success, img = cap.read()
if not success:
break
# Perform object tracking on the current frame
img = tracker.track_objects(img)
# Display the resulting frame
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(), from ultralytics import YOLO
class ObjectDetection:
"""
A class for object detection using a YOLO model.
Attributes:
model (YOLO): The YOLO model used for detection.
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_path="yolo-Weights/yolov8n.pt"):
"""
Initializes the ObjectDetection class with the specified YOLO model.
Args:
model_path (str): The path to the YOLO model weights.
"""
self.model = YOLO(model_path)
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_objects(self, img):
"""
Detects objects in the given image.
Args:
img (numpy.ndarray): The image in which to detect objects.
Returns:
list: A list of detections, each containing class name, bounding box coordinates, width, height, and confidence.
"""
results = self.model(img, stream=True)
detections = []
for r in results:
for box in r.boxes:
# Get the confidence score
confidence = box.conf[0].item()
if confidence < 0.55:
continue # Skip detections below confidence threshold
# Get the class index
cls = int(box.cls[0])
if cls not in self.allowed_classes:
continue # Skip classes that are not allowed
# Get bounding box coordinates
x1, y1, x2, y2 = map(int, box.xyxy[0])
width, height = x2 - x1, y2 - y1
class_name = self.classNames[cls]
detections.append((class_name, x1, y1, width, height, confidence))
return detections`, `import cv2
from deep_sort_realtime.deepsort_tracker import DeepSort
from datetime import datetime, timedelta
from Status import Status
class ObjectTracker:
"""
A class for tracking objects using Deep Sort and updating their status in the database.
Attributes:
db (Database): The database instance for storing object data.
detection_model (ObjectDetection): The object detection model.
tracker (DeepSort): The Deep Sort tracker instance.
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.
"""
self.db = db
self.detection_model = detection_model
# Initialize the Deep Sort tracker with specified parameters
self.tracker = DeepSort(max_age=10, n_init=3, nms_max_overlap=1.0,
max_cosine_distance=0.4, nn_budget=None)
self.object_positions = {} # To store positions of each object
def is_near(self, existing_obj, new_obj, threshold=30):
"""
Determines if a new object is near an existing object based on a threshold.
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).
threshold (int, optional): The distance threshold to consider.
Returns:
bool: True if the objects are near each other, False otherwise.
"""
ex, ey, ew, eh = existing_obj
nx, ny, nw, nh = new_obj
# Check if bounding boxes are close enough
return not (nx > ex + ew + threshold or
nx + nw < ex - threshold or
ny > ey + eh + threshold or
ny + nh < ey - threshold)
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):
"""
Performs object detection and tracking on the given image.
Args:
img (numpy.ndarray): The image on which to perform tracking.
Returns:
numpy.ndarray: The image with tracking annotations.
"""
frame_height, frame_width = img.shape[:2]
detections = self.detection_model.detect_objects(img)
formatted_detections = []
for class_name, x1, y1, width, height, confidence in detections:
new_obj = (x1, y1, width, height)
# Prepare detections for the tracker
formatted_detections.append(([x1, y1, width, height], confidence, class_name))
# Draw bounding boxes and labels on the image
cv2.rectangle(img, (x1, y1), (x1 + width, y1 + height), (255, 0, 255), 3)
cv2.putText(img, f'{class_name} {confidence:.2f}', (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)
existing_objs = self.db.fetch_objects(class_name)
preexisting_obj = False
obj_id = None
# Check if the detected object matches any existing object in the database
for existing_obj in existing_objs:
db_x1 = existing_obj[2]
db_y1 = existing_obj[3]
db_width = existing_obj[4]
db_height = existing_obj[5]
last_seen = datetime.fromisoformat(existing_obj[6])
status = Status(existing_obj[7])
if self.is_near((db_x1, db_y1, db_width, db_height), new_obj):
preexisting_obj = True
obj_id = existing_obj[0] # Get the ID
# Update the existing object's position and reset its status to 'In Frame'
self.db.update_object(obj_id, x1, y1, width, height)
# Update position history
self.object_positions[obj_id] = [(x1, y1, width, height)]
break # Update only one matching object
if not preexisting_obj:
# Insert a new object into the database
obj_id = self.db.insert_object(class_name, x1, y1, width, height)
# Initialize position history
self.object_positions[obj_id] = [(x1, y1, width, height)]
else:
# Update position history
self.object_positions[obj_id] = [(x1, y1, width, height)]
# Ensure the object's status is 'In Frame'
self.db.update_status(obj_id, Status.IN_FRAME)
# Update the tracker with new detections
tracks = self.tracker.update_tracks(formatted_detections, frame=img)
# Check for objects that may have left the frame
self.check_for_false_positives(frame_width, frame_height)
return img`, `from enum import Enum
class Status(str, Enum):
"""
An enumeration to represent the status of tracked objects.
"""
IN_FRAME = "In Frame"
LEFT_FRAME = "Left Frame"`, implement face recognition with ArcFace or similar so if an object of class name person is detected, see if their face matches someones, and if it does see if the name of that match is in the database for an entity and if so the person detected is the same as the person in the database with that name. This will require a new field in database record for person name.
To implement face recognition with ArcFace or a similar model in your object tracking system, allowing for identification of detected persons, follow these steps:
Modify the Database Schema
Add a new field person_name to your database to store the names of recognized individuals. Update your create_table method in the Database class to include this field:
def create_table(self):
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS tracked_objects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
class_name TEXT,
x1 INTEGER,
y1 INTEGER,
width INTEGER,
height INTEGER,
last_seen DATETIME,
status TEXT,
detection_count INTEGER DEFAULT 0,
person_name TEXT
)
''')
self.conn.commit()
Make sure to handle the person_name field in your insert and update methods.
Integrate a Face Recognition Model
Use ArcFace for face recognition. The insightface library provides an implementation of ArcFace and is suitable for this purpose. Install it using:
pip install insightface opencv-python-headless
Create a new class FaceRecognizer for handling face recognition:
# face_recognizer.py
import insightface
from insightface.app import FaceAnalysis
import numpy as np
import cv2
import os
class FaceRecognizer:
def __init__(self, known_faces_dir='known_faces'):
self.face_analyzer = FaceAnalysis(providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
self.face_analyzer.prepare(ctx_id=0, nms=0.4)
self.known_faces = {} # Mapping from name to embedding
self.register_known_faces(known_faces_dir)
def register_known_faces(self, known_faces_dir):
"""
Registers all known faces from a directory.
"""
for filename in os.listdir(known_faces_dir):
if filename.endswith('.jpg') or filename.endswith('.png'):
name = os.path.splitext(filename)[0]
img_path = os.path.join(known_faces_dir, filename)
img = cv2.imread(img_path)
self.register_known_face(name, img)
def register_known_face(self, name, img):
"""
Registers a single known face.
"""
faces = self.face_analyzer.get(img)
if faces:
face = faces[0]
embedding = face.embedding
self.known_faces[name] = embedding
def recognize_face(self, img):
"""
Recognizes a face in an image.
"""
faces = self.face_analyzer.get(img)
if faces:
face = faces[0]
embedding = face.embedding
min_distance = float('inf')
identity = None
for name, ref_embedding in self.known_faces.items():
distance = np.linalg.norm(embedding - ref_embedding)
if distance < min_distance:
min_distance = distance
identity = name
# Set a threshold for recognition (adjust as needed)
if min_distance < 1.0:
return identity, min_distance
return None, None
In this code:
We load known faces from a directory called known_faces.
Faces are represented by their embeddings calculated by the model.
Recognition is done by comparing embeddings of detected faces with known embeddings.
Detect and Recognize Faces in Detected Persons
Modify the ObjectTracker class to include face recognition when a 'person' is detected:
from face_recognizer import FaceRecognizer
class ObjectTracker:
def __init__(self, db, detection_model):
self.db = db
self.detection_model = detection_model
self.face_recognizer = FaceRecognizer() # Initialize the face recognizer
# ... existing initialization ...
def track_objects(self, img):
# ... existing code ...
for class_name, x1, y1, width, height, confidence in detections:
if class_name == 'person':
# Focus on the face region
person_roi = img[y1:y1+height, x1:x1+width]
# Recognize the face
person_name, distance = self.face_recognizer.recognize_face(person_roi)
if person_name:
# Update the database record with the person's name
self.db.update_person_name(obj_id, person_name)
# Annotate the image with the recognized name
cv2.putText(img, f'{person_name} {confidence:.2f}', (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
else:
cv2.putText(img, f'Unknown {confidence:.2f}', (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
else:
# ... existing code for other classes ...
pass
# ... existing code for updating positions and database ...
Update the Database Handling for Person Names
Add a method to update the person_name field in your Database class:
class Database:
# ... existing methods ...
def update_person_name(self, obj_id, person_name):
"""
Updates the person_name field for an object in the database.
Args:
obj_id (int): The ID of the object to update.
person_name (str): The recognized person's name.
"""
self.cursor.execute('''
UPDATE tracked_objects
SET person_name=?
WHERE id=?
''', (person_name, obj_id))
self.conn.commit()
Implement Face Detection within the Person Bounding Box
Since the person bounding box might include the entire body, you need to extract the face region for recognition. The FaceRecognizer class already handles this using the insightface library's face detection capabilities.
Prepare a Dataset of Known Faces
Create a directory known_faces in your project.
Add images of known individuals to this directory, naming each image with the person's name (e.g., john_doe.jpg).
Ensure the images are clear and only include the face.
Optimize for Performance
Face recognition can be computationally intensive. To optimize:
Use a GPU if available by setting ctx_id=0 when preparing the FaceAnalysis instance.
Consider resizing images or adjusting the face detection parameters for speed.
Limit face recognition to when a person is first detected or at intervals rather than every frame.
Update Display and Annotations
In your track_objects method, update the display annotations to include the recognized person's name, as shown in step 3.
Test Thoroughly
Test your system with images of the known individuals to ensure they are recognized correctly.
Adjust the distance threshold in the recognize_face method as needed.
Ensure that unknown individuals are not incorrectly recognized as known individuals.
Privacy and Ethical Considerations
Be mindful of privacy laws and ethical guidelines when implementing face recognition.
Ensure you have consent from individuals whose faces are stored and recognized.
By following these steps, you'll enhance your object tracking system to recognize and identify individuals when a person is detected. This integration of face recognition will allow you to not only track persons but also associate them with known identities, provided they are registered in your dataset.
Example of the Updated ObjectTracker Class:
import cv2
from deep_sort_realtime.deepsort_tracker import DeepSort
from datetime import datetime, timedelta
from Status import Status
from face_recognizer import FaceRecognizer
class ObjectTracker:
# ... existing initialization ...
def track_objects(self, img):
frame_height, frame_width = img.shape[:2]
detections = self.detection_model.detect_objects(img)
formatted_detections = []
for class_name, x1, y1, width, height, confidence in detections:
new_obj = (x1, y1, width, height)
# Prepare detections for the tracker
formatted_detections.append(([x1, y1, width, height], confidence, class_name))
obj_id = None # Will remain None if no match is found
if class_name == 'person':
# Crop the face region from the person bounding box
person_roi = img[y1:y1+height, x1:x1+width]
person_name, distance = self.face_recognizer.recognize_face(person_roi)
if person_name:
# Update database and display the name
# Assume you have a method to get or create obj_id
obj_id = self.get_or_create_obj_id(class_name, x1, y1, width, height)
self.db.update_person_name(obj_id, person_name)
cv2.putText(img, f'{person_name} {confidence:.2f}', (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
else:
# Handle unknown person
cv2.putText(img, f'Unknown {confidence:.2f}', (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
else:
# Handle other classes
cv2.putText(img, f'{class_name} {confidence:.2f}', (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)
# Draw bounding box
cv2.rectangle(img, (x1, y1), (x1 + width, y1 + height), (255, 0, 255), 3)
# Update or insert object in the database
if obj_id is not None:
self.db.update_object(obj_id, x1, y1, width, height)
else:
obj_id = self.db.insert_object(class_name, x1, y1, width, height)
# Update position history
self.object_positions[obj_id] = [(x1, y1, width, height)]
# Update the tracker with new detections
tracks = self.tracker.update_tracks(formatted_detections, frame=img)
# Check for objects that may have left the frame
self.check_for_false_positives(frame_width, frame_height)
return img
def get_or_create_obj_id(self, class_name, x1, y1, width, height):
# Implement logic to get an existing object ID or create a new one
# For simplicity, always create a new one in this example
return self.db.insert_object(class_name, x1, y1, width, height)
Notes:
The get_or_create_obj_id method is a placeholder. Implement logic to check if the object already exists in the database based on proximity or DeepSort tracking ID.
Ensure that face recognition is performed efficiently to maintain real-time performance.
By carefully integrating face recognition into your existing object detection and tracking pipeline, you enrich the system's capabilities, enabling it to not only detect and track persons but also identify them if they are known. Ensure that you manage system resources effectively and maintain good programming practices to keep the system robust and maintainable.