-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetection_engine.py
More file actions
144 lines (117 loc) · 4.79 KB
/
Copy pathdetection_engine.py
File metadata and controls
144 lines (117 loc) · 4.79 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""
Detection Engine
Handles YOLOv8 object detection and target matching
"""
import logging
from typing import List, Dict, Any, Optional, Tuple
import numpy as np
from ultralytics import YOLO
import time
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class DetectionEngine:
"""YOLOv8-based object detection engine with target matching"""
def __init__(self, model_path: str = "yolov8s.pt", confidence_threshold: float = 0.5):
"""
Initialize detection engine
Args:
model_path: Path to YOLO model file
confidence_threshold: Minimum confidence for detections
"""
self.model_path = model_path
self.confidence_threshold = confidence_threshold
self.model: Optional[YOLO] = None
self.class_names: List[str] = []
self.total_detections = 0
self.target_detections = 0
def load_model(self) -> bool:
"""
Load YOLO model
Returns:
True if model loaded successfully
"""
try:
logger.info(f"Loading YOLO model: {self.model_path}")
self.model = YOLO(self.model_path)
self.class_names = list(self.model.names.values())
logger.info(f"Model loaded successfully. Classes: {len(self.class_names)}")
return True
except Exception as e:
logger.error(f"Error loading YOLO model: {e}")
# Try to load default model as fallback
if self.model_path != "yolov8s.pt":
logger.info("Attempting to load default model (yolov8s.pt) as fallback")
try:
self.model = YOLO("yolov8s.pt")
self.class_names = list(self.model.names.values())
self.model_path = "yolov8s.pt"
logger.info("Default model loaded successfully")
return True
except Exception as fallback_error:
logger.error(f"Failed to load fallback model: {fallback_error}")
return False
def detect(self, frame: np.ndarray, target_classes: Optional[List[str]] = None) -> List[Dict[str, Any]]:
"""
Run detection on frame
Args:
frame: Input frame (BGR format)
target_classes: Optional list of target class names to filter
Returns:
List of detection dictionaries
"""
if self.model is None:
logger.error("Model not loaded. Call load_model() first.")
return []
try:
# Run inference
results = self.model(frame, conf=self.confidence_threshold, verbose=False)
detections = []
# Process results
for result in results:
boxes = result.boxes
for i, box in enumerate(boxes):
# Extract box data
xyxy = box.xyxy[0].cpu().numpy() # Bounding box coordinates
conf = float(box.conf[0].cpu().numpy()) # Confidence
cls = int(box.cls[0].cpu().numpy()) # Class ID
class_name = self.model.names[cls]
# Check if this is a target class
if target_classes and class_name not in target_classes:
continue
detection = {
'class': class_name,
'class_id': cls,
'confidence': round(conf, 4),
'bbox': [int(xyxy[0]), int(xyxy[1]), int(xyxy[2]), int(xyxy[3])],
'frame_id': self.total_detections
}
detections.append(detection)
self.total_detections += 1
if target_classes and class_name in target_classes:
self.target_detections += 1
return detections
except Exception as e:
logger.error(f"Error during detection: {e}")
return []
def get_class_names(self) -> List[str]:
"""Get list of all available class names"""
return self.class_names
def validate_target_class(self, target_class: str) -> bool:
"""
Check if target class exists in model
Args:
target_class: Class name to validate
Returns:
True if class exists in model
"""
return target_class.lower() in [name.lower() for name in self.class_names]
def get_stats(self) -> Dict[str, int]:
"""Get detection statistics"""
return {
'total_detections': self.total_detections,
'target_detections': self.target_detections
}
def reset_stats(self):
"""Reset detection counters"""
self.total_detections = 0
self.target_detections = 0