import cv2
from skimage.transform import resize
import numpy as np


face_cascade = cv2.CascadeClassifier("Face-Clock/model/cv2/haarcascade_frontalface_alt2.xml")
print("人臉偵測cascade分類器載入完成")

# 人臉偵測處理回傳結果矩陣
image_size=160
def face_cropped(img,faces, margin):    
    aligned_images = []
    for f in faces:
        (x, y, w, h) = f
        cropped = img[y-margin//2:y+h+margin//2,x-margin//2:x+w+margin//2, :]
        aligned = resize(cropped, (image_size, image_size), mode='reflect')
        aligned_images.append(aligned)
    return np.array(aligned_images)

def get_face(img):
    faces = face_cascade.detectMultiScale(img,scaleFactor=1.1,minNeighbors=3)
    if(len(faces)==0):
        return '偵測不到人臉請重新調整'
    else:
        return faces,face_cropped(img,faces,10)