Spaces:
Sleeping
Sleeping
Create unattended_object.py
Browse files- unattended_object.py +47 -0
unattended_object.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
from ultralytics import YOLO
|
| 4 |
+
import os
|
| 5 |
+
import uuid
|
| 6 |
+
|
| 7 |
+
# Load YOLOv8 model (can be customized for object detection)
|
| 8 |
+
model = YOLO("yolov8n.pt") # You may switch to yolov8s.pt or yolov8m.pt based on size/accuracy
|
| 9 |
+
|
| 10 |
+
# Maintain state of detected objects for simple tracking
|
| 11 |
+
unattended_objects_memory = {}
|
| 12 |
+
|
| 13 |
+
def detect_unattended_objects(frame, frame_index, detection_interval=30, stay_threshold=90):
|
| 14 |
+
"""
|
| 15 |
+
Detects unattended objects such as bags that appear in the same position for too long.
|
| 16 |
+
Returns True and the cropped object image if detected.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
detections = model.predict(source=frame, classes=[24, 26, 28, 39], verbose=False)[0]
|
| 20 |
+
# COCO classes for suitcase (24), handbag (26), backpack (28), and cardboard box (39)
|
| 21 |
+
|
| 22 |
+
h, w, _ = frame.shape
|
| 23 |
+
detected = False
|
| 24 |
+
cropped_output = None
|
| 25 |
+
|
| 26 |
+
for result in detections.boxes:
|
| 27 |
+
cls = int(result.cls[0])
|
| 28 |
+
conf = float(result.conf[0])
|
| 29 |
+
x1, y1, x2, y2 = map(int, result.xyxy[0])
|
| 30 |
+
|
| 31 |
+
center = ((x1 + x2) // 2, (y1 + y2) // 2)
|
| 32 |
+
object_id = f"{cls}-{center[0]//20}-{center[1]//20}" # simple spatial bin id
|
| 33 |
+
|
| 34 |
+
if object_id not in unattended_objects_memory:
|
| 35 |
+
unattended_objects_memory[object_id] = frame_index
|
| 36 |
+
else:
|
| 37 |
+
duration = frame_index - unattended_objects_memory[object_id]
|
| 38 |
+
if duration >= stay_threshold:
|
| 39 |
+
detected = True
|
| 40 |
+
cropped_output = frame[y1:y2, x1:x2]
|
| 41 |
+
unattended_objects_memory[object_id] = frame_index + 9999 # suppress repeated detection
|
| 42 |
+
|
| 43 |
+
# Clear memory periodically
|
| 44 |
+
if frame_index % (stay_threshold * 2) == 0:
|
| 45 |
+
unattended_objects_memory.clear()
|
| 46 |
+
|
| 47 |
+
return detected, cropped_output
|