Sunday, April 27, 2025

Anti_Sleeping_project_AI

import cv2
import serial
import time

# Initialize Serial Communication with Arduino
# Update 'COM3' to your Arduino COM port (for Linux, it might be '/dev/ttyACM0')
arduino = serial.Serial('COM3', 9600)
time.sleep(2)  # Give some time for Arduino to reset

# Load Haar cascade classifiers
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

if face_cascade.empty():
    print("Error: Face cascade file not loaded!")

if eye_cascade.empty():
    print("Error: Eye cascade file not loaded!")

cap = cv2.VideoCapture(0)

while True:
    ret, img = cap.read()
    if not ret:
        print("Failed to grab frame")
        break

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    if len(faces) == 0:
        # No face detected
        arduino.write(b'0')  # Buzzer OFF
    else:
        # Face detected
        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = img[y:y+h, x:x+w]

            eyes = eye_cascade.detectMultiScale(roi_gray)

            if len(eyes) == 0:
                # Face detected but Eyes closed
                cv2.putText(img, "Eyes Closed", (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
                arduino.write(b'1')  # Buzzer ON
            else:
                # Face detected and Eyes open
                for (ex, ey, ew, eh) in eyes:
                    cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 127, 255), 2)
                arduino.write(b'0')  # Buzzer OFF

    cv2.imshow('Face & Eye Detection', img)

    if cv2.waitKey(30) & 0xFF == 27:  # Press 'ESC' to exit
        break

cap.release()
arduino.close()
cv2.destroyAllWindows()






# Arduino code

int buzzerPin = 8; // connect buzzer to pin 8

void setup() {
  Serial.begin(9600);
  pinMode(buzzerPin, OUTPUT);
  digitalWrite(buzzerPin, LOW); // Initially buzzer OFF
}

void loop() {
  if (Serial.available() > 0) {
    char data = Serial.read();

    if (data == '1') {
      digitalWrite(buzzerPin, HIGH); // Eyes closed -> buzzer ON
    }
    else if (data == '0') {
      digitalWrite(buzzerPin, LOW);  // Eyes open or no face -> buzzer OFF
    }
  }
}



No comments:

Post a Comment

MUD Three Mode operation Manual Automatic GPS

 Code for three mode operation: /*   3-Mode Headlight Controller   - Manual mode (driver uses a toggle to pick high/low)   - Auto mode (LDR...