#!/usr/bin/env python
import numpy as np
import cv2
from utils.mlcode import recognize_face
from utils.face_fetch import fetch_face_coords, align_faces, preprocess_face

if __name__=='__main__':
    cap = cv2.VideoCapture(0)
    cap.set(cv2.CAP_PROP_POS_MSEC, 50)
    coords = None
    while True:
        ret, frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        coords = fetch_face_coords(gray)
        if len(coords)==0:
            cv2.putText(frame, 'No face detected!', (100,400), cv2.FONT_HERSHEY_SIMPLEX,
                        1, (0,0,255), 2)
        for rect in coords:
            (x, y, w, h) = rect.left(), rect.top(), rect.width(), rect.height()
            face = preprocess_face(align_faces(frame, gray, rect))
            nameId = recognize_face(face) or 'Unknown'
            cv2.rectangle(frame,(x, y), (x+w, y+h), (255,0,0),2)
            cv2.putText(frame, nameId, (min(x+2, 640),max(y-2, 0)), cv2.FONT_HERSHEY_SIMPLEX,
                        0.6, (255,0,0), 2)
        cv2.putText(frame, "press 'q' to quit!", (10,470), cv2.FONT_HERSHEY_SIMPLEX,
                    0.6, (0,0,0), 2)
        cv2.imshow('face recognizer',    frame)
        if cv2.waitKey(1) & 0xFF == ord('q'): break
    cap.release()
    cv2.destroyAllWindows()
