Untitled

 avatar
unknown
plain_text
a month ago
2.1 kB
4
Indexable
import cv2

# Load Haar cascade files for face and eyes
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

def detect_face_and_eyes(frame):
    # Convert to grayscale for better performance
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces in the frame
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    
    for (x, y, w, h) in faces:
        # Draw a rectangle around the face
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

        # Region of interest (ROI) for eyes within the detected face
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = frame[y:y+h, x:x+w]

        # Detect eyes within the face ROI
        eyes = eye_cascade.detectMultiScale(roi_gray, scaleFactor=1.1, minNeighbors=10, minSize=(15, 15))
        
        if len(eyes) >= 2:
            eye_status = "Eyes Open"
        else:
            eye_status = "Eyes Closed"

        # Display eye status on the frame
        cv2.putText(frame, eye_status, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

        # Draw rectangles around the eyes
        for (ex, ey, ew, eh) in eyes:
            cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)

    return frame

def main():
    # Start the webcam or video stream
    cap = cv2.VideoCapture(0)  # Change to video file path if using a video

    while True:
        ret, frame = cap.read()
        if not ret:
            print("Error: Unable to read from camera or video.")
            break

        # Detect faces and eyes
        frame = detect_face_and_eyes(frame)

        # Display the output
        cv2.imshow("Face and Eye Detection", frame)

        # Press 'q' to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release the capture and close windows
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
Leave a Comment