driver drowsiness

mail@pastecode.io avatar
unknown
python
2 years ago
1.6 kB
3
Indexable
Never
import tensorflow as tf
import cv2
import numpy as np

cap = cv2.VideoCapture(0)
model = tf.keras.models.load_model('models/CNN-163216-80k.h5')
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_lefteye_2splits.xml')

while True:
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    # if a face is detected
    if len(faces) > 0:
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
            roi_gray_eye = gray[y-(int(h/2)):y+h, x:x+w]
            roi_color_eye = frame[y-(int(h/2)):y+h, x:x+w]

            eyes = eye_cascade.detectMultiScale(roi_gray_eye)
            for (eex,eey,eew,eeh) in eyes:
                cv2.rectangle(roi_color_eye, (eex, eey), (eex+eew, eey+eeh), (0, 255, 0), 2)

                img = cv2.resize(roi_color_eye, (256, 256))
                img = np.reshape(img, [1, 256, 256, 3])
                img = img / 255.0
                prediction = model.predict(img)
                if prediction > 0.5:
                    cv2.putText(frame, f'OPEN EYES {prediction} !!', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
                else:
                    cv2.putText(frame, f'CLOSED EYES {prediction} !!', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)


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

cap.release()
cv2.destroyAllWindows()