File size: 2,687 Bytes
6715b3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from typing import List, Dict, Optional
import os
from ultralytics import YOLO
import cv2 # For loading image to get dimensions if needed

# Load the YOLOv8 model once when the module is imported
# We'll use a small, general-purpose model. You can choose others like yolov8n.pt, yolov8s.pt, etc.
# Or even a custom-trained model path.
model = YOLO("yolov8x.pt")

def detect_objects(frame_path: str, labels: Optional[List[str]] = None) -> List[Dict]:
    """Runs object detection on a frame using YOLOv8; optionally filters by labels.
    
    Args:
        frame_path: Path to the image frame.
        labels: A list of class names to filter by (e.g., ['person', 'car']).
                If None, all detected objects are returned.
                YOLO class names can be found at: https://docs.ultralytics.com/datasets/coco/#classes

    Returns:
        A list of dictionaries, where each dictionary represents a detected object
        and contains 'label' (class name), 'confidence' (0-1), and 'bbox' ([x_min, y_min, x_max, y_max]).
    """
    if not os.path.exists(frame_path):
        raise FileNotFoundError(f"Frame file not found: {frame_path}")

    results = model(frame_path, verbose=False)  # verbose=False to reduce console output
    detected_objects = []

    # Process results list
    for result in results:
        boxes = result.boxes  # Boxes object for bounding box outputs
        names = result.names  # Class names

        for i in range(len(boxes)):
            class_id = int(boxes.cls[i])
            class_name = names[class_id]
            confidence = float(boxes.conf[i])
            bbox_tensor = boxes.xyxy[i] # [x_min, y_min, x_max, y_max]
            bbox = [int(coord) for coord in bbox_tensor.tolist()] # Convert to list of ints

            if labels is None or class_name in labels:
                detected_objects.append({
                    "label": class_name,
                    "confidence": confidence,
                    "bbox": bbox,
                    "frame_path": frame_path # Optional: add frame path for context
                })
    
    print(f"Detected {len(detected_objects)} objects in {frame_path} (filtered by: {labels if labels else 'All'}).")
    return detected_objects

# Example usage (for testing):
# if __name__ == '__main__':
#     # Create a dummy image file for testing
#     import numpy as np
#     dummy_image_path = "dummy_frame.png"
#     cv2.imwrite(dummy_image_path, np.zeros((640, 480, 3), dtype=np.uint8)) 
#     
#     detections = detect_objects(dummy_image_path, labels=['person', 'bicycle'])
#     print(detections)
#     if os.path.exists(dummy_image_path):
#        os.remove(dummy_image_path)