main.py 4.09 KB
import cv2
import numpy as np
import dlib
import light_remover as lr
import imutils
from imutils import face_utils
from imutils.video import VideoStream
from keras.models import load_model
import pygame


def main():
    leye = cv2.CascadeClassifier('pre_trained/haarcascade_lefteye_2splits.xml')
    reye = cv2.CascadeClassifier('pre_trained/haarcascade_righteye_2splits.xml')
    model = load_model('model/eyes_weight.h5')

    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor('pre_trained/shape_predictor_68_face_landmarks.dat')

    pygame.mixer.init()
    warning_sound = pygame.mixer.Sound('asset/windsheld.mp3')
    danger_sound = pygame.mixer.Sound('asset/pullup.mp3')

    video = VideoStream(src=0).start()

    # const
    font = cv2.FONT_HERSHEY_COMPLEX_SMALL
    target_size = (24,24)

    # variable
    status = 0 # 0: stay awake, 1: drowsy, 2: sleep
    both_eyes_closed_count = 0

    def get_eye_open(frame, bound) -> bool:
        for (x,y,w,h) in bound:
            eye = frame[y:y+h, x:x+w] 
            cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2) # Paint eye bound box
            eye = cv2.cvtColor(eye, cv2.COLOR_BGR2GRAY) # using only for reshaping 
            eye = cv2.resize(eye, target_size) 
            eye = eye/255
            eye = eye.reshape(24, 24, -1)
            eye = np.expand_dims(eye, axis=0)
            prob = model.predict(eye, verbose=0)
            pred = prob.argmax(axis=-1) 
            return True if pred[0] == 1 else False

    def get_eye_open_dlib(frame, bound):
        l, r = min(map(lambda x: x[0], bound)), max(map(lambda x: x[0], bound))
        t, b = min(map(lambda x: x[1], bound)), max(map(lambda x: x[1], bound))
        cv2.rectangle(frame, (l,t), (r,b), (0,255,0), 2)

    while True:
        frame = video.read()
        frame = imutils.resize(frame, width=640)
        height, width = frame.shape[:2] 
        cv2.rectangle(frame, (0, height-50), (200, height), (255,0,0), thickness=cv2.FILLED)

        L, gray = lr.light_removing(frame)
        left_eye = leye.detectMultiScale(gray)
        right_eye =  reye.detectMultiScale(gray)
        rects = detector(gray, 0)

        left_eye_open = get_eye_open(frame, left_eye)
        right_eye_open = get_eye_open(frame, right_eye)
 
        # For each detected face, find the landmark.
        for (i, rect) in enumerate(rects):
          # Make the prediction and transfom it to numpy array
          shape = predictor(gray, rect)
          shape = face_utils.shape_to_np(shape)
    
          r_eye = shape[36:42]
          l_eye = shape[42:48]   
          mouth = shape[48:]
          get_eye_open_dlib(frame, r_eye)
          get_eye_open_dlib(frame, l_eye)
          
          for (x, y) in mouth:
            cv2.circle(frame, (x, y), 2, (0, 255, 0), -1)

        both_eyes_closed = False
        if left_eye_open != None or right_eye_open != None:
            both_eyes_closed = not left_eye_open and not right_eye_open

        if both_eyes_closed:
            both_eyes_closed_count += 1
        else:
            both_eyes_closed_count = max(both_eyes_closed_count - 1, 0)
        cv2.putText(frame, "Closed" if both_eyes_closed else "Open", (10, height-20), font, 1, (255,255,255), 1, cv2.LINE_AA)

        cv2.putText(frame, f"Count: {both_eyes_closed_count}", (100, height-20), font, 1, (255,255,255), 1, cv2.LINE_AA)

        if both_eyes_closed_count < 15:
            if status != 0:
                warning_sound.stop()
            status = 0
        elif both_eyes_closed_count < 50:
            if status != 1:
                danger_sound.stop()
                warning_sound.play(-1)
            cv2.rectangle(frame, (0,0), (width,height), (0,0,255), both_eyes_closed_count // 5) 
            status = 1
        else:
            if status != 2:
                warning_sound.stop()
                danger_sound.play(-1)
            cv2.rectangle(frame, (0,0), (width,height), (0,0,255), 20) 
            status = 2

        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cv2.destroyAllWindows()    
    video.stop()

if __name__ == '__main__':
  main()