Change this code so instead of washeadingout function use a is within frame function…
- User
Change this code so instead of was_heading_out function use a is within frame function that checks if an object is near a border and if for example its near the left border, if width is small, its out of bounds.: `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 last two 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 the last two 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 was_heading_out(self, obj_id, frame_width, frame_height): """ Determines if the object was heading out of the frame based on its last positions. 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. Returns: bool: True if the object was heading out of the frame, False otherwise. """ positions = self.object_positions.get(obj_id, []) if len(positions) < 2: return False # Not enough data to determine direction # Get the last two positions (x1, y1, w1, h1) = positions[-2] (x2, y2, w2, h2) = positions[-1] # Calculate movement vector dx = x2 - x1 dy = y2 - y1 # Determine if moving towards a border moving_left = dx < 0 and x2 <= 0 moving_right = dx > 0 and x2 + w2 >= frame_width moving_up = dy < 0 and y2 <= 0 moving_down = dy > 0 and y2 + h2 >= frame_height # If moving towards any edge of the frame return moving_left or moving_right or moving_up or moving_down 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 was heading out of the 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 < 5: # 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 was heading out of frame when last seen if self.was_heading_out(obj_id, frame_width, frame_height): # Update the object's status to 'Left Frame' self.db.update_status(obj_id, Status.LEFT_FRAME) else: # Keep the status as 'In Frame' or update as needed pass 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 positions = self.object_positions.get(obj_id, []) if len(positions) < 2: self.object_positions[obj_id] = [(db_x1, db_y1, db_width, db_height), (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), (x1, y1, width, height)] else: self.object_positions[obj_id] = [self.object_positions[obj_id][1], (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` - Assistant