# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import os
import tensorflow as tf
from tensorflow import keras

img_ht = 180
img_wt = 180


import cv2

cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier("/home/hp77/miniconda3/envs/tunex/share/opencv4/haarcascades/haarcascade_frontalface_default.xml")

import numpy as np

model = tf.keras.models.load_model('EmoDet1/')

class_names = ['0', '1', '2', '3', '4', '5', '6']
Emotion = {
    '0' : 'Afraid',
    '1' : 'Angry',
    '2' : 'Disgust',
    '3' : 'Happy',
    '4' : 'Nervous',
    '5' : 'Sad',
    '6' : 'Surprise'
}

import PIL
import PIL.Image

writer = None
(W, H) = (None, None)
x, y = (0, 0)
crop_img=None

# +
while True:
    ret, frame = cap.read()
    print("It came here 1st") 
    if not ret:
        print("It came here 2nd")
        break
    if W is None or H is None:
        (H, W) = frame.shape[:2]
    output = frame.copy()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.1, 4)

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 2)
        crop_img = frame[x:x+w, y:y+h]
    cv2.imshow("cropped", frame)
    #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    crop_img = cv2.cvtColor(crop_img, cv2.COLOR_BGR2RGB)
    #frame = cv2.resize(frame, (img_ht, img_wt)).astype("float32")
    crop_img = cv2.resize(crop_img, (img_ht, img_wt)).astype("float32")
    #img_array = keras.preprocessing.image.img_to_array(img) commented because I am doing preprocessing with cv2
    #img_array = tf.expand_dims(frame, 0) # Create a batch
    crop_img_array = tf.expand_dims(crop_img, 0)
    #predictions = model.predict(img_array)
    predicitons_crop = model.predict(crop_img_array)
    #score = tf.nn.softmax(predictions[0])
    score_crop = tf.nn.softmax(predictions_crop[0])
    
    #text = "E: {}, C: {}".format(Emotion[class_names[np.argmax(score)]], 100*np.max(score))
    text_crop = "E: {}, C: {}".format(Emotion[class_names[np.argmax(score_crop)]], 100*np.max(score))
    #cv2.putText(output, text, (35, 50), cv2.FONT_HERSHEY_SIMPLEX,1.25, (0, 255, 0), 5)
    cv2.putText(output, text_crop, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (0,255,0), 5)
    
    cv2.imshow("Output", output)
    key = cv2.waitKey(1) & 0xFF
    
    if key == ord("q"):
        break

print("[INFO] cleaning up...")
#writer.release()
cap.release()

# -



StarcoderdataJupyterScriptsDedupFiltered