#currently an open cv tutorial

import numpy as np
import cv2

from PIL import Image

import argparse

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

parser = argparse.ArgumentParser()
parser.add_argument('-i', '--image', required=True, help='path to image')
parser.add_argument('-o', '--outfile', nargs='?', default='fedorified.png')
args = parser.parse_args()

#face = 'me.jpg'
face = args.image
fedora = 'fedora_clean.png'

pil_img = Image.open(face)
fedora_img = Image.open(fedora)
(fedorawidth, fedoraheight) = fedora_img.size


cv_img = cv2.imread(face)
gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    cv2.rectangle(cv_img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = cv_img[y:y+h, x:x+w]
    #justfedorathings
    scaled_height = int((w / float(fedorawidth)) * fedoraheight)
    # make fedora a little bigger than face so brim goes beyond side of head a bit
    scaled_fedora = fedora_img.resize((int(1.1*w), int(1.1*scaled_height)))
    # fedora sits down on the head a little
    pil_img.paste(scaled_fedora, (x, y-(3*scaled_height/4)), scaled_fedora)
    
#pil_img.save('fedorafied.png')
pil_img.save(args.outfile)