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
)
''')
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 update_object(self, obj_id, x1, y1, width, height):
"""
Updates the position and size of an existing object in the database.
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.
"""
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=?
WHERE id=?
''', (x1, y1, width, height, last_seen, status, obj_id))
self.conn.commit()
def insert_object(self, class_name, x1, y1, width, height):
"""
Inserts a new object into the database.
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.
"""
last_seen = datetime.datetime.now().isoformat()
status = Status.IN_FRAME.value # Set status to 'In Frame'
self.cursor.execute('''
INSERT INTO tracked_objects (class_name, x1, y1, width, height, last_seen, status)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (class_name, x1, y1, width, height, last_seen, status))
self.conn.commit()
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()`,`# Import necessary libraries
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)
code
# 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.
code
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.
code
Attributes:
db (Database): The database instance for storing object data.
detection_model (ObjectDetection): The object detection model.
tracker (DeepSort): The Deep Sort tracker instance.
"""
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)
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 check_for_lost_objects(self):
"""
Checks the database for objects that haven't been seen for more than 10 seconds and updates their status.
"""
all_objects = self.db.fetch_all_objects()
now = datetime.now()
ten_seconds_ago = now - timedelta(seconds=10)
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]
last_seen = datetime.fromisoformat(last_seen_str)
# If the object hasn't been seen for more than 10 seconds and its status is 'In Frame'
if last_seen < ten_seconds_ago and status == Status.IN_FRAME.value:
# 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:
existing_objs = self.db.fetch_objects(class_name)
new_obj = (x1, y1, width, height)
preexisting_obj = False
# Check if the detected object matches any existing object in the database
for existing_obj in existing_objs:
db_x1, db_y1, db_width, db_height = existing_obj[2], existing_obj[3], existing_obj[4], existing_obj[5]
if self.is_near((db_x1, db_y1, db_width, db_height), new_obj):
preexisting_obj = True
# Update the existing object's position and reset its status to 'In Frame'
self.db.update_object(existing_obj[0], x1, y1, width, height)
break # Update only one matching object
if not preexisting_obj:
# Insert a new object into the database
self.db.insert_object(class_name, 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)
# 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_lost_objects()
return img`. For this Python code, fix the proximity to the frame border part of the code as is does not work. Also, if something has only been detected a few times its probably fake so delete items from database if they've only been detected x times like 10 .
To address the issues you've encountered in your Python object tracking system, we'll make the following enhancements:
Fixing Proximity to Frame Border: Implement a reliable mechanism to determine whether detected objects are near the borders of the video frame. If objects are near the borders, you can highlight them differently or take specific actions as needed.
Handling Low-Confidence Detections: Introduce a system to track how often each object is detected. If an object has been detected fewer than a specified number of times (e.g., 10), it will be considered a false detection and removed from the database.
Below are detailed steps and code modifications to implement these features.
1. Enhancing the Database Class
A. Add detection_count to Track Detections
To track how many times each object has been detected, we'll add a detection_count column to the tracked_objects table. This count increments each time an object is detected again, helping us determine whether an object is valid or likely a false detection.
Updated Database Class:
python
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.
If the table exists, ensures that the 'detection_count' column is present.
"""
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 1
)
''')
self.conn.commit()
# Check if 'detection_count' column exists; add it if missing
self.cursor.execute("PRAGMA table_info(tracked_objects)")
columns = [info[1] for info in self.cursor.fetchall()]
if 'detection_count' not in columns:
self.cursor.execute("ALTER TABLE tracked_objects ADD COLUMN detection_count INTEGER DEFAULT 1")
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 update_object(self, obj_id, x1, y1, width, height):
"""
Updates the position and size of an existing object in the database,
increments its detection count, and updates the last seen timestamp.
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.
"""
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()
def insert_object(self, class_name, x1, y1, width, height):
"""
Inserts a new object into the database with an initial detection count.
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.
"""
last_seen = datetime.datetime.now().isoformat()
status = Status.IN_FRAME.value # Set status to 'In Frame'
detection_count = 1 # Initialize detection count
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()
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_low_count_objects(self, min_count=10):
"""
Deletes objects from the database that have a detection_count less than min_count.
Args:
min_count (int, optional): The minimum detection count required for an object to remain in the database.
"""
self.cursor.execute('''
DELETE FROM tracked_objects
WHERE detection_count < ?
''', (min_count,))
self.conn.commit()
def close(self):
"""
Closes the database connection.
"""
self.conn.close()
Key Modifications:
Added detection_count Column: The create_table method now includes a detection_count column with a default value of 1. Additionally, it checks if the column exists and adds it if missing to support existing databases.
Increment detection_count: The update_object method now increments the detection_count each time an object is updated (i.e., detected again).
Initialize detection_count: The insert_object method initializes detection_count to 1 when inserting a new object.
Delete Low-Count Objects: Added the delete_low_count_objects method to remove objects that have been detected fewer than min_count times.
Close Database Connection: Added a close method to properly close the database connection when done.
2. Enhancing the ObjectTracker Class
A. Implement Proximity to Frame Border
We'll add functionality to check whether detected objects are near the edges of the frame. If an object is within a specified threshold (e.g., 30 pixels) from any border, we'll annotate it differently.
B. Handle Low-Confidence Detections
After tracking, we'll delete objects from the database that have been detected fewer than 10 times to filter out likely false positives.
Updated ObjectTracker Class:
python
Key Modifications:
Added is_near_border Method: Determines if an object is within a specified threshold (border_threshold, default 30 pixels) from any edge of the frame.
Annotated Border-Proximate Objects: In the track_objects method, after drawing bounding boxes, the code checks if the object is near the border. If so, it draws an additional red border and labels the object as "Near Border."
Deleted Low-Count Objects: After processing detections and tracking, the method calls delete_low_count_objects to remove objects that have been detected fewer than min_detection_count times (default 10).
Border Threshold and Min Detection Count as Parameters: These values are now parameters in the __init__ method, making it easy to adjust as needed.
3. Ensuring the Status Enum is Defined Correctly
Make sure your Status enum includes all necessary statuses. Based on your current usage, it should at least include IN_FRAME and LEFT_FRAME.
Example Status Enum:
python
from enum import Enum
class Status(Enum):
IN_FRAME = "In Frame"
LEFT_FRAME = "Left Frame"
Ensure this enum is correctly defined in your Status module and that it's imported wherever necessary.
4. Updating the Main Script
Ensure that your main script initializes the ObjectTracker with the appropriate parameters and manages the lifecycle of the database connection.
Updated main Function:
python
# Import necessary libraries
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, border_threshold=30, min_detection_count=10)
try:
# Set up video capture from the default webcam
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # Set width
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) # Set height
while True:
success, img = cap.read()
if not success:
print("Failed to read from webcam. Exiting...")
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'):
print("Exit signal received. Exiting...")
break
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Release resources
cap.release()
cv2.destroyAllWindows()
db.close()
if __name__ == "__main__":
main()
Key Modifications:
Initialization of ObjectTracker: Now passing border_threshold=30 and min_detection_count=10 as arguments to set the proximity threshold and minimum detection count.
Exception Handling: Wrapped the main loop in a try-except-finally block to ensure resources are released properly even if an error occurs.
Closing the Database: Ensured that the database connection is closed in the finally block.
5. Additional Recommendations
A. Performance Optimization
Batch Database Operations: If your application deals with a high number of detections, consider batching database updates to improve performance.
Indices on Database Columns: Adding indices on frequently queried columns (e.g., class_name) can speed up database operations.
B. Enhanced Object Matching
Use More Reliable Matching Criteria: Instead of simple proximity checks, consider using intersection-over-union (IoU) or other more sophisticated methods to match detected objects with existing database entries.
Incorporate Object IDs: Utilizing unique IDs from trackers like DeepSort can help maintain consistent tracking and database updates.
C. Handling Edge Cases
Reappearing Objects: If an object leaves the frame and re-enters, decide whether to treat it as a new object or match it with its previous entry based on some criteria.
Dynamic Thresholds: Adjust border_threshold and min_detection_count dynamically based on the application's context or performance metrics.
6. Testing the Enhancements
After implementing the above changes, thoroughly test your system to ensure:
Proximity Detection: Objects near the borders are correctly identified and annotated.
Detection Count Handling: Objects that are detected fewer than the specified number of times are removed from the database.
Overall Performance: The system maintains real-time performance without significant slowdowns.
Database Integrity: Verify that the database accurately reflects the current state of tracked objects, including their detection counts and statuses.
By following these modifications and recommendations, your object tracking system will be more robust, accurately handle proximity to frame borders, and effectively manage low-confidence detections to maintain a clean and reliable database.
If you encounter any issues during implementation or need further assistance with specific parts of the code, feel free to ask!
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.
border_threshold (int): The number of pixels defining the border proximity.
min_detection_count (int): The minimum number of detections required to keep an object.
"""
def __init__(self, db, detection_model, border_threshold=30, min_detection_count=10):
"""
Initializes the ObjectTracker class with the given database and detection model.
Args:
db (Database): The database instance.
detection_model (ObjectDetection): The object detection model.
border_threshold (int, optional): Pixel threshold for border proximity.
min_detection_count (int, optional): Minimum detections to keep an object.
"""
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.border_threshold = border_threshold
self.min_detection_count = min_detection_count
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_near_border(self, x1, y1, width, height, frame_width, frame_height):
"""
Determines if the object is near the frame borders.
Args:
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.
frame_width (int): The width of the frame.
frame_height (int): The height of the frame.
Returns:
bool: True if the object is near any border, False otherwise.
"""
x2 = x1 + width
y2 = y1 + height
return (x1 <= self.border_threshold or
y1 <= self.border_threshold or
x2 >= frame_width - self.border_threshold or
y2 >= frame_height - self.border_threshold)
def check_for_lost_objects(self):
"""
Checks the database for objects that haven't been seen for more than 10 seconds and updates their status.
"""
all_objects = self.db.fetch_all_objects()
now = datetime.now()
ten_seconds_ago = now - timedelta(seconds=10)
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 10 seconds and its status is 'In Frame'
if last_seen < ten_seconds_ago and status == Status.IN_FRAME.value:
# 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:
existing_objs = self.db.fetch_objects(class_name)
new_obj = (x1, y1, width, height)
preexisting_obj = False
# Check if the detected object matches any existing object in the database
for existing_obj in existing_objs:
db_x1, db_y1, db_width, db_height = existing_obj[2], existing_obj[3], existing_obj[4], existing_obj[5]
if self.is_near((db_x1, db_y1, db_width, db_height), new_obj):
preexisting_obj = True
# Update the existing object's position and reset its status to 'In Frame'
self.db.update_object(existing_obj[0], x1, y1, width, height)
break # Update only one matching object
if not preexisting_obj:
# Insert a new object into the database
self.db.insert_object(class_name, 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)
# Check and annotate proximity to frame borders
if self.is_near_border(x1, y1, width, height, frame_width, frame_height):
# Draw a red border around the object if it's near the frame borders
cv2.rectangle(img, (x1, y1), (x1 + width, y1 + height), (0, 0, 255), 3)
cv2.putText(img, 'Near Border', (x1, y1 + height + 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
# Update the tracker with new detections
tracks = self.tracker.update_tracks(formatted_detections, frame=img)
# (Optional) You can process tracks if needed, e.g., drawing track IDs
# Check for objects that may have left the frame
self.check_for_lost_objects()
# Delete objects with low detection counts
self.db.delete_low_count_objects(self.min_detection_count)
return img