Spaces:
Sleeping
Sleeping
Update src/detection/strategies/cnn_model.py
Browse files
src/detection/strategies/cnn_model.py
CHANGED
|
@@ -5,26 +5,24 @@ import torch
|
|
| 5 |
import torchvision.transforms as transforms
|
| 6 |
from torchvision.models import efficientnet_b7
|
| 7 |
import cv2
|
| 8 |
-
import dlib
|
| 9 |
from PIL import Image
|
| 10 |
import os
|
| 11 |
|
| 12 |
class CnnProcessor(BaseProcessor):
|
| 13 |
"""
|
| 14 |
Drowsiness detection using a pre-trained EfficientNet-B7 model.
|
|
|
|
| 15 |
"""
|
| 16 |
def __init__(self, config):
|
| 17 |
self.settings = config['cnn_model_settings']
|
| 18 |
self.model_path = self.settings['model_path']
|
| 19 |
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
self.face_detector = dlib.get_frontal_face_detector()
|
| 23 |
|
| 24 |
-
# Load the model
|
| 25 |
self.model = self._load_model()
|
| 26 |
|
| 27 |
-
# Define image transformations
|
| 28 |
self.transform = transforms.Compose([
|
| 29 |
transforms.Resize((224, 224)),
|
| 30 |
transforms.ToTensor(),
|
|
@@ -35,66 +33,61 @@ class CnnProcessor(BaseProcessor):
|
|
| 35 |
"""Loads the EfficientNet-B7 model and custom weights."""
|
| 36 |
if not os.path.exists(self.model_path):
|
| 37 |
print(f"Error: Model file not found at {self.model_path}")
|
| 38 |
-
print("Please run 'python download_model.py' first.")
|
| 39 |
return None
|
| 40 |
|
| 41 |
try:
|
| 42 |
-
# Initialize the model structure
|
| 43 |
model = efficientnet_b7()
|
| 44 |
-
# Modify the final classifier layer to match the number of output classes (e.g., 2: drowsy, not_drowsy)
|
| 45 |
num_ftrs = model.classifier[1].in_features
|
| 46 |
-
model.classifier[1] = torch.nn.Linear(num_ftrs, 2)
|
| 47 |
-
|
| 48 |
-
# Load the saved weights
|
| 49 |
model.load_state_dict(torch.load(self.model_path, map_location=self.device))
|
| 50 |
model.to(self.device)
|
| 51 |
-
model.eval()
|
| 52 |
print(f"CNN Model '{self.model_path}' loaded successfully on {self.device}.")
|
| 53 |
return model
|
| 54 |
except Exception as e:
|
| 55 |
print(f"Error loading CNN model: {e}")
|
| 56 |
return None
|
| 57 |
|
| 58 |
-
def process_frame(self, frame):
|
| 59 |
"""
|
| 60 |
-
Processes a frame
|
| 61 |
"""
|
| 62 |
-
if self.model is None:
|
| 63 |
return frame, {"cnn_prediction": False}
|
| 64 |
|
| 65 |
-
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 66 |
-
faces = self.face_detector(gray)
|
| 67 |
is_drowsy_prediction = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
pil_image = Image.fromarray(cv2.cvtColor(face_crop, cv2.COLOR_BGR2RGB))
|
| 81 |
image_tensor = self.transform(pil_image).unsqueeze(0).to(self.device)
|
| 82 |
|
| 83 |
-
# Perform inference
|
| 84 |
with torch.no_grad():
|
| 85 |
outputs = self.model(image_tensor)
|
| 86 |
_, preds = torch.max(outputs, 1)
|
| 87 |
-
|
| 88 |
-
print(preds)
|
| 89 |
-
if preds.item() == 1:
|
| 90 |
is_drowsy_prediction = True
|
| 91 |
|
| 92 |
-
# Draw bounding box for visualization
|
| 93 |
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 255, 0), 2)
|
| 94 |
label = "Drowsy" if is_drowsy_prediction else "Awake"
|
| 95 |
cv2.putText(frame, f"CNN: {label}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2)
|
| 96 |
|
| 97 |
-
# Process only the first detected face
|
| 98 |
-
break
|
| 99 |
-
|
| 100 |
return frame, {"cnn_prediction": is_drowsy_prediction}
|
|
|
|
| 5 |
import torchvision.transforms as transforms
|
| 6 |
from torchvision.models import efficientnet_b7
|
| 7 |
import cv2
|
|
|
|
| 8 |
from PIL import Image
|
| 9 |
import os
|
| 10 |
|
| 11 |
class CnnProcessor(BaseProcessor):
|
| 12 |
"""
|
| 13 |
Drowsiness detection using a pre-trained EfficientNet-B7 model.
|
| 14 |
+
This version receives face landmarks from another processor instead of using dlib.
|
| 15 |
"""
|
| 16 |
def __init__(self, config):
|
| 17 |
self.settings = config['cnn_model_settings']
|
| 18 |
self.model_path = self.settings['model_path']
|
| 19 |
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 20 |
|
| 21 |
+
# dlib is no longer needed.
|
| 22 |
+
# self.face_detector = dlib.get_frontal_face_detector()
|
| 23 |
|
|
|
|
| 24 |
self.model = self._load_model()
|
| 25 |
|
|
|
|
| 26 |
self.transform = transforms.Compose([
|
| 27 |
transforms.Resize((224, 224)),
|
| 28 |
transforms.ToTensor(),
|
|
|
|
| 33 |
"""Loads the EfficientNet-B7 model and custom weights."""
|
| 34 |
if not os.path.exists(self.model_path):
|
| 35 |
print(f"Error: Model file not found at {self.model_path}")
|
|
|
|
| 36 |
return None
|
| 37 |
|
| 38 |
try:
|
|
|
|
| 39 |
model = efficientnet_b7()
|
|
|
|
| 40 |
num_ftrs = model.classifier[1].in_features
|
| 41 |
+
model.classifier[1] = torch.nn.Linear(num_ftrs, 2)
|
|
|
|
|
|
|
| 42 |
model.load_state_dict(torch.load(self.model_path, map_location=self.device))
|
| 43 |
model.to(self.device)
|
| 44 |
+
model.eval()
|
| 45 |
print(f"CNN Model '{self.model_path}' loaded successfully on {self.device}.")
|
| 46 |
return model
|
| 47 |
except Exception as e:
|
| 48 |
print(f"Error loading CNN model: {e}")
|
| 49 |
return None
|
| 50 |
|
| 51 |
+
def process_frame(self, frame, face_landmarks=None):
|
| 52 |
"""
|
| 53 |
+
Processes a frame using the CNN model with pre-supplied landmarks.
|
| 54 |
"""
|
| 55 |
+
if self.model is None or face_landmarks is None:
|
| 56 |
return frame, {"cnn_prediction": False}
|
| 57 |
|
|
|
|
|
|
|
| 58 |
is_drowsy_prediction = False
|
| 59 |
+
h, w, _ = frame.shape
|
| 60 |
+
|
| 61 |
+
landmarks = face_landmarks[0].landmark
|
| 62 |
+
|
| 63 |
+
# Calculate bounding box from landmarks
|
| 64 |
+
x_coords = [lm.x * w for lm in landmarks]
|
| 65 |
+
y_coords = [lm.y * h for lm in landmarks]
|
| 66 |
+
x1, y1 = int(min(x_coords)), int(min(y_coords))
|
| 67 |
+
x2, y2 = int(max(x_coords)), int(max(y_coords))
|
| 68 |
|
| 69 |
+
# Add some padding to the bounding box
|
| 70 |
+
padding = 10
|
| 71 |
+
x1 = max(0, x1 - padding)
|
| 72 |
+
y1 = max(0, y1 - padding)
|
| 73 |
+
x2 = min(w, x2 + padding)
|
| 74 |
+
y2 = min(h, y2 + padding)
|
| 75 |
+
|
| 76 |
+
# Crop the face
|
| 77 |
+
face_crop = frame[y1:y2, x1:x2]
|
| 78 |
+
|
| 79 |
+
if face_crop.size > 0:
|
| 80 |
pil_image = Image.fromarray(cv2.cvtColor(face_crop, cv2.COLOR_BGR2RGB))
|
| 81 |
image_tensor = self.transform(pil_image).unsqueeze(0).to(self.device)
|
| 82 |
|
|
|
|
| 83 |
with torch.no_grad():
|
| 84 |
outputs = self.model(image_tensor)
|
| 85 |
_, preds = torch.max(outputs, 1)
|
| 86 |
+
if preds.item() == 1: # Assuming class 1 is 'drowsy'
|
|
|
|
|
|
|
| 87 |
is_drowsy_prediction = True
|
| 88 |
|
|
|
|
| 89 |
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 255, 0), 2)
|
| 90 |
label = "Drowsy" if is_drowsy_prediction else "Awake"
|
| 91 |
cv2.putText(frame, f"CNN: {label}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2)
|
| 92 |
|
|
|
|
|
|
|
|
|
|
| 93 |
return frame, {"cnn_prediction": is_drowsy_prediction}
|