|
import cv2 |
|
import numpy as np |
|
from ultralytics import YOLO |
|
import torch |
|
import os |
|
|
|
|
|
print(f"MPS available: {torch.backends.mps.is_available()}") |
|
|
|
|
|
model = YOLO('best.pt') |
|
if torch.backends.mps.is_available(): |
|
model.to('mps') |
|
|
|
|
|
class_names = ['safe driving', 'drinking', 'eating', 'hair and makeup', 'operating radio', 'talking on phone', 'talking to passenger'] |
|
|
|
|
|
cap = cv2.VideoCapture(0) |
|
if not cap.isOpened(): |
|
print("Error: Could not open webcam.") |
|
exit() |
|
|
|
|
|
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320) |
|
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 320) |
|
|
|
def trigger_alarm(action): |
|
"""Trigger an alarm if the action is not 'safe driving'.""" |
|
if action != 'safe driving': |
|
print(f"ALARM: Unsafe behavior detected - {action}!") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
while cap.isOpened(): |
|
|
|
ret, frame = cap.read() |
|
if not ret: |
|
print("Error: Could not read frame.") |
|
break |
|
|
|
|
|
results = model(frame, conf=0.1) |
|
|
|
|
|
display_text = "Safe driving" |
|
for result in results: |
|
boxes = result.boxes.xyxy.cpu().numpy() |
|
scores = result.boxes.conf.cpu().numpy() |
|
classes = result.boxes.cls.cpu().numpy() |
|
|
|
if len(boxes) > 0: |
|
|
|
max_score_idx = scores.argmax() |
|
detected_action = class_names[int(classes[max_score_idx])] |
|
confidence = scores[max_score_idx] |
|
display_text = f"{detected_action}: {confidence:.2f}" |
|
|
|
trigger_alarm(detected_action) |
|
|
|
|
|
cv2.putText(frame, display_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) |
|
|
|
|
|
cv2.imshow('YOLO Webcam Detection', frame) |
|
|
|
|
|
if cv2.waitKey(1) & 0xFF == ord('q'): |
|
break |
|
|
|
|
|
cap.release() |
|
cv2.destroyAllWindows() |