# Python Code for Eye Detection and Light Control
import cv2
import mediapipe as mp
import serial
import time
# Initialize MediaPipe Face Mesh
mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5)
# Initialize serial communication with Arduino
ser = serial.Serial('COM4', 9600) # Replace 'COM4' with your Arduino port
time.sleep(2)
# Open webcam
cap = cv2.VideoCapture(0)
def calculate_eye_aspect_ratio(landmarks, eye_indices):
# Calculate the eye aspect ratio to determine if eyes are closed
left_point = landmarks[eye_indices[0]]
right_point = landmarks[eye_indices[3]]
top_point = landmarks[eye_indices[1]]
bottom_point = landmarks[eye_indices[5]]
# Horizontal distance (width)
horizontal_length = ((right_point[0] - left_point[0]) ** 2 + (right_point[1] - left_point[1]) ** 2) ** 0.5
# Vertical distance (height)
vertical_length = ((bottom_point[0] - top_point[0]) ** 2 + (bottom_point[1] - top_point[1]) ** 2) ** 0.5
return vertical_length / horizontal_length
while True:
# Capture frame-by-frame
success, image = cap.read()
if not success:
break
# Convert the BGR image to RGB
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Process the image and find face mesh
results = face_mesh.process(rgb_image)
if results.multi_face_landmarks:
for face_landmarks in results.multi_face_landmarks:
landmarks = [(int(lm.x * image.shape[1]), int(lm.y * image.shape[0])) for lm in face_landmarks.landmark]
# Indices for the right eye (can change to left eye if needed)
right_eye_indices = [33, 160, 158, 133, 153, 144]
# Calculate Eye Aspect Ratio (EAR) for the right eye
ear = calculate_eye_aspect_ratio(landmarks, right_eye_indices)
# Threshold to determine if the eye is closed
if ear < 0.2:
# Eyes closed, turn off the light
ser.write(b'0\n')
cv2.putText(image, "Eyes Closed - Light OFF", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
else:
# Eyes open, turn on the light
ser.write(b'1\n')
cv2.putText(image, "Eyes Open - Light ON", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Eye Control for Light', image)
# Break the loop when 'q' key is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the capture and close windows
cap.release()
cv2.destroyAllWindows()
ser.close()
/* Arduino Code for Light Control */
int ledPin = 13; // LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // Start serial communication
}
void loop() {
if (Serial.available() > 0) {
char state = Serial.read(); // Read the incoming data
if (state == '1') {
digitalWrite(ledPin, HIGH); // Turn on the LED
} else if (state == '0') {
digitalWrite(ledPin, LOW); // Turn off the LED
}
}
}