import tensorflow as tf
from tensorflow import keras
import numpy as np
import cv2
from keras.models import load_model
import numpy as np

facedectect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')


cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
font = cv2.FONT_HERSHEY_COMPLEX


model = load_model('keras_model.h5', compile= False)
def get_classname(classNo):
    if classNo == 0:
        return "Siwat"
    elif classNo == 1:
        return "Sukatat"
    elif classNo == 2:
        return "Sorapat"

while True:
    sucess, imgOriginal = cap.read()
    faces = facedectect.detectMultiScale(imgOriginal,1.3,5)
    for x,y,w,h in faces:
        crop_img = imgOriginal[y:y+h, x:x+h]
        img = cv2.resize(crop_img, (224,224))
        img = img.reshape(1, 224, 224, 3)
        prediction = model.predict(img)
        classIndex = np.argmax(prediction,axis=1)
        #classIndex = model.predict(img)
        probabilityValue = np.amax(prediction)

        if classIndex == 0:
            cv2.rectangle(imgOriginal, (x,y), (x+w, y+h), (0,255,0), 2)
            cv2.rectangle(imgOriginal, (x,y-40), (x+w, y), (0,255,0), -2)
            cv2.putText(imgOriginal, str(get_classname(classIndex)), (x,y-10), font, 0.75, (0,255,0), 2, cv2.LINE_AA, False)
            print(str(get_classname(classIndex)))
        elif classIndex == 1:
            cv2.rectangle(imgOriginal, (x,y), (x+w, y+h), (0,255,0), 2)
            cv2.rectangle(imgOriginal, (x,y-40), (x+w, y), (0,255,0), -2)
            cv2.putText(imgOriginal, str(get_classname(classIndex)), (x,y-10), font, 0.75, (0,255,0), 2, cv2.LINE_AA, False)
            print(str(get_classname(classIndex)))
        elif classIndex == 2:
            cv2.rectangle(imgOriginal, (x,y), (x+w, y+h), (0,255,0), 2)
            cv2.rectangle(imgOriginal, (x,y-40), (x+w, y), (0,255,0), -2)
            cv2.putText(imgOriginal, str(get_classname(classIndex)), (x,y-10), font, 0.75, (0,255,0), 2, cv2.LINE_AA, False)
            print(str(get_classname(classIndex)))

        cv2.putText(imgOriginal, str(round(probabilityValue*100, 2))+ "%", (180,75), font ,0.75, (0,255,0), 2, cv2.LINE_AA, False)
    cv2.imshow("Result", imgOriginal)
    k = cv2.waitKey(1)
    if k == ord('q'):
        break
video.release()
cv2.destroyAllWindows()
    
        


        