lokesh341 commited on
Commit
b9024f3
·
verified ·
1 Parent(s): 3efd80c

Create object_detection.py

Browse files
Files changed (1) hide show
  1. services/object_detection.py +54 -0
services/object_detection.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from ultralytics import YOLO
4
+ from typing import List, Tuple, Dict, Any
5
+
6
+ # Load YOLOv8 model for general object detection
7
+ model = YOLO("models/yolov8n.pt")
8
+
9
+ def detect_objects(frame: np.ndarray) -> Tuple[List[Dict[str, Any]], np.ndarray]:
10
+ """
11
+ Detect cars, bikes, humans, dogs, and other objects in the frame using YOLOv8.
12
+ Args:
13
+ frame: Input frame as a numpy array.
14
+ Returns:
15
+ Tuple of (list of detections, annotated frame).
16
+ """
17
+ # Perform inference
18
+ results = model(frame, conf=0.5) # Detect all classes with confidence > 0.5
19
+
20
+ detections = []
21
+ for i, r in enumerate(results[0].boxes):
22
+ x_min, y_min, x_max, y_max = map(int, r.xyxy[0])
23
+ conf = float(r.conf)
24
+ cls = int(r.cls)
25
+ # Map YOLOv8 class IDs to labels (based on COCO dataset)
26
+ label_map = {
27
+ 0: "person", # Human
28
+ 1: "bicycle", # Bike (approximation)
29
+ 2: "car",
30
+ 3: "motorcycle", # Bike
31
+ 5: "bus", # Treat as car
32
+ 7: "truck", # Treat as car
33
+ 16: "dog",
34
+ }
35
+ dtype = label_map.get(cls, "object") # Default to "object" for unmapped classes
36
+ if dtype in ["bicycle", "motorcycle"]:
37
+ dtype = "bike"
38
+ elif dtype in ["bus", "truck"]:
39
+ dtype = "car"
40
+ label = f"{dtype.capitalize()} {i+1}"
41
+
42
+ # Determine severity (not used for objects, but included for consistency)
43
+ area = (x_max - x_min) * (y_max - y_min)
44
+ severity = "Moderate" # Default for objects
45
+
46
+ detections.append({
47
+ "box": [x_min, y_min, x_max, y_max],
48
+ "label": label,
49
+ "type": dtype,
50
+ "confidence": conf,
51
+ "severity": severity
52
+ })
53
+
54
+ return detections, frame