#! /usr/bin/env python3
import sys
import numpy as np
import cv2

# Get user supplied values

cascPath = "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
cascPath2 = "/usr/share/opencv/haarcascades/haarcascade_mcs_eyepair_big.xml"

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
eyeCascade = cv2.CascadeClassifier(cascPath2)


if sys.argv[1].isdigit():
    video_capture = cv2.VideoCapture(int(sys.argv[1]))
else:
    video_capture = cv2.VideoCapture(sys.argv[1])

deletesmaller = True


# Read the image
while video_capture.isOpened():
    ret, frame = video_capture.read()
    if frame is None:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    #continue
    # Detect faces in the image
    faces = faceCascade.detectMultiScale(gray, scaleFactor=1.4, minNeighbors=5, minSize=(30, 30),
                                     flags=cv2.CASCADE_SCALE_IMAGE)

    # eliminate duplicates
    faces2=[]
    for (x, y, w, h) in faces:
        for elem in faces2:
            x2, y2, w2, h2 = elem
            if (x2>=x and x2+w2<=x+w) and (y2>=y and y2+h2<=y+h):
                #print("dup face found!")
                if deletesmaller:
                    break
                else:
                    faces2.remove(elem)
            if (x>=x2 and x+w<=x2+w2) and (y>=y2 and y+h<=y2+h2):
                #print("dup face found!")
                if deletesmaller:
                    faces2.remove(elem)
                else:
                    break
        else:
            faces2.append((x, y, w, h))
    
    #print ("Found {0} faces!".format(len(faces2)))
    # Draw a rectangle around the faces
    for (x, y, w, h) in faces2:
            roi = gray[y:y+h, x:x+w]
            eyes = eyeCascade.detectMultiScale(
                roi,
                scaleFactor=1.4,
                minNeighbors=5,
                minSize=(30, 30),
                flags = cv2.cv.CV_HAAR_SCALE_IMAGE)
            if len(eyes) in [1, 2]:
                (x3, y3, w3, h3) = eyes[0]
                cv2.rectangle(frame, (x+x3, y+y3), (x+x3+w3, y+y3+h3), (0, 255, 0), 2)
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
            #returnval, filtered = cv2.threshold(~roi, 120, 255, cv2.THRESH_BINARY)
            #contours, returnval = cv2.findContours(filtered, cv2.cv.CV_RETR_EXTERNAL, cv2.cv.CV_CHAIN_APPROX_NONE);
            #if contours is not None: # and len(circles) >= 2:
            #    for elem in contours:
            #        rect = cv2.boundingRect(elem)
            #        area = cv2.contourArea(elem)
            #        radius = rect[2]
            #        if area >= 30 and abs(1 - (rect[2] / rect[3])) <= 0.2 and abs(1 - (area / (3.14 * pow(radius, 2)))) <= 0.2:
            #            #print("gotcha")
            #            cv2.circle(roi, (rect[0] + radius, rect[1]+radius), radius, (255,0,0), 2);
                    
                #print(contours)
            #frame[y:y+h, x:x+w] = cv2.cvtColor(roi,cv2.COLOR_GRAY2BGR)
            
    
    #circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1.6, 3);
    #if circles is not None: # and len(circles) >= 2:
    #    print(circles)
        #circles = np.round(circles[0, :]).astype("int")
        #for (x3,y3,r3) in circles:
        #    print(x3,y3,r3)
        #    cv2.circle(frame, (x3, y3), r3, (0, 255, 0), 4)
    cv2.imshow("Faces found", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

