#!/usr/bin/env python
# coding=utf-8
import cv2
import os
import time
from PIL import Image,ImageDraw
i=0
true_num=0


def detectFaces(image_name,Type="Haar"):
    img = cv2.imread(image_name)
    h,w,z=img.shape
    cascadeType={"Haar":"./cascade.xml","LBP":"../LBP/cascade.xml"}
    for ih in range(0,h):
        for iw in range(0,w/2):
            img[ih][iw]=img[0][0]
            if ih > h/3:
                img[ih][iw*2]=img[0][0]
    face_cascade = cv2.CascadeClassifier(cascadeType[Type])
    if img.ndim == 3:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else:
        gray = img #if语句：如果img维度为3，说明不是灰度图，先转化为灰度图gray，如果不为3，也就是2，原图就是灰度图
    for i in range(0,5):
        faces = face_cascade.detectMultiScale(gray,1.1, i)
        if len(faces) ==1:
            break 
        #1.3和5是特征的最小、最大检测窗口，它改变检测结果也会改变
    result = []
    for (x,y,width,height) in faces:
        result.append((x,y,x+width,y+height))
    return result

#def detectFaces_haar(image_name):
#    img = cv2.imread(image_name)
#
#    h,w,v=img.shape
#    
#    for ih in range(0,h):
#        for iw in range(0,w/2):
#            img[ih][iw]=img[0][0]
#            if ih > h/3:
#                img[ih][iw*2]=img[0][0]
#    
#    face_cascade = cv2.CascadeClassifier("../LBP/cascade.xml")
#    if img.ndim == 3:
#        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#    else:
#        gray = img #if语句：如果img维度为3，说明不是灰度图，先转化为灰度图gray，如果不为3，也就是2，原图就是灰度图
#    for i in range(0,5):
#        faces = face_cascade.detectMultiScale(gray,1.1, i)
#        if len(faces) ==1:
#            break 
#        #1.3和5是特征的最小、最大检测窗口，它改变检测结果也会改变
#    result = []
#    for (x,y,width,height) in faces:
#        result.append((x,y,x+width,y+height))
#    return result
#


def drawFaces(image_name):
        global i
        global true_num
        stime=time.time()


        path,filename=os.path.split(image_name)
        faces = detectFaces(image_name,"LBP")
        faces_haar = detectFaces(image_name,"Haar")

        img = Image.open(image_name)
        draw_instance = ImageDraw.Draw(img)
        flag=""
        flag2=""
        if  faces_haar:
            for (xh1,yh1,xh2,yh2) in faces_haar:
                draw_instance.rectangle((xh1,yh1,xh2,yh2), outline=(0,255,0))
                flag="h"
            print "h:",faces_haar

        if faces:
            for (x1,y1,x2,y2) in faces:
                draw_instance.rectangle((x1,y1,x2,y2), outline=(255, 0,0))
                flag2="l"

            print 'l:',faces
        if faces != [] or faces_haar !=[]:
            true_num+=1
        img.save('/home/dvaliu/true/'+str(i)+"_"+flag+flag2+"_"+filename)
        print i
        i+=1

        print time.time()-stime

PATH_Test = "../../../Pictures/WWU/"

for  img in os.listdir(PATH_Test): 
    #print (detectFaces(PATH_Test+img))
    drawFaces(PATH_Test+img)
print str(true_num)+'/'+str(i)
    

