Spaces:
Build error
Build error
Download tools/detect_objects.py from arashx07/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 2.69 kB
-
https://huggingface.co/spaces/arashx07/Final_Assignment_Template/resolve/main/tools/detect_objects.py
- Command line
-
hf download hf://spaces/arashx07/Final_Assignment_Template/tools/detect_objects.py
-
curl -L -o detect_objects.py https://huggingface.co/spaces/arashx07/Final_Assignment_Template/resolve/main/tools/detect_objects.py
2.69 kB
| 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) | |