import face_recognition
import cv2
import datetime
import csv
import os
from PIL import Image, ImageDraw, ImageFont
import numpy as np

from scipy.spatial import distance as dist
from imutils import face_utils
import argparse
import imutils
import time
import dlib
import random

def faces_paths(folder):
    faces_list = []
    for path, subdirs, files in os.walk(folder):
        for name in files:
            if not name.startswith('.'):
                faces_list.append( os.path.join(path, name))
    return faces_list

def load_feature_face(picture_list):
    a_encodings =[]
    for a in picture_list:
        file = face_recognition.load_image_file(a)
        if file is None: continue
        face_locations = face_recognition.face_locations(file)
        encodings = face_recognition.face_encodings(file, face_locations)

        if encodings is None or len(encodings)<=0: continue
        a_encodings.append(encodings[0])
    return a_encodings


from threading import Thread
from time import sleep

def threaded_function(arg):
    for i in range(arg):
        print("running")
        sleep(1)

print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(r'./shape_predictor_68_face_landmarks.dat')

# start the video stream thread
print("[INFO] starting video stream thread...")
textColor = (255, 0, 0)

mypath_a = "Name/"
a_list = faces_paths(mypath_a)
known_face_encodings = load_feature_face(a_list)

video_capture = cv2.VideoCapture(0)

known_face_names = a_list

# Initialize variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

scale_ratio = 0.5
font = ImageFont.truetype("SimSun.ttf", 30, encoding="utf-8")

checking_name = False
checking_name_count = 130

ret, frame = video_capture.read()

while ret:
    # Grab a single frame of video
    ret, frame = video_capture.read()
    # Resize frame of video to 1/4 size for faster face recognition processing
    small_frame = cv2.resize(frame, (0, 0), fx=scale_ratio, fy=scale_ratio)
    
    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        
        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding,0.4)
            name = "Name/未知.png"

            # If a match was found in known_face_encodings, just use the first one.
            if True in matches:
                first_match_index = matches.index(True)
                name = known_face_names[first_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame

    has_identity_people = False
    
    # Display the results
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        sr = int(1/scale_ratio)
        top *= sr
        right *= sr
        bottom *= sr
        left *= sr

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        board_height = int((bottom-top)/5)
        # Draw a label with a name below the face
        cv2.rectangle(frame, (left, bottom - board_height), (right, bottom), (0, 0, 255), cv2.FILLED)

        lable_name = name[5:-4]
        frame_pil = Image.fromarray(frame)  #转为PIL的图片格式
        draw = ImageDraw.Draw(frame_pil)
        text_size = font.getsize(lable_name)
        ImageDraw.Draw(frame_pil).text((left + ((right-left)-text_size[0])/2, bottom - board_height+(board_height-text_size[1])/2), name[5:-4], (255, 255, 255), font)
        frame = np.array(frame_pil)


    # Display the resulting image
    cv2.imshow('Video', frame)

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()
