#!/usr/bin/env python
import os,time
import datetime
import opencv.adaptors
from opencv.cv import *
from opencv import highgui
import Image
    
def get_image(camera):
    testimage = highgui.cvQueryFrame(camera)	
    time.sleep(1)
    im = highgui.cvQueryFrame(camera)
    dir(im)
    print "l'image est prise"
    return opencv.adaptors.Ipl2PIL(im)

def detectObjects(image):
	grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1)
  	cvCvtColor(image, grayscale, CV_BGR2GRAY)
  	storage = cvCreateMemStorage(0)
  	cvClearMemStorage(storage)
  	cvEqualizeHist(grayscale, grayscale)
  	cascade = cvLoadHaarClassifierCascade('/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml',cvSize(1,1))
  	faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.2, 2,CV_HAAR_DO_CANNY_PRUNING, cvSize(50,50))

  	if faces:
    		for f in faces:
	      		print("[(%d,%d) -> (%d,%d)]" % (f.x, f.y, f.x+f.width, f.y+f.height))     

a=os.popen('whoami')
l=a.read()
s=l.split('\n')
uname=s[0]
    
now = datetime.datetime.now()
now = str(now)
   
im=None
camera= highgui.cvCreateCameraCapture(1)
time.sleep(2)
im = get_image(camera)
os.chdir('/home/%s/Pictures' %(uname) )
fname='image_'+uname+"_"+now+'.png'
im.save(fname, "PNG")
image=cvLoadImage(fname)
detectObjects(image)
