import io
import time
from picamera import PiCamera
import cv2        
import numpy as np
from threading import Thread
from time import sleep
from timeit import default_timer as timer


w=576
h=512
fw=(w+31)//32*32
fh=(h+15)//16*16
frame=None
t=None
camera=PiCamera()
camera.resolution = (w, h)
camera.vflip=True
camera.framerate = 41
camera.exposure_mode='auto'
camera.awb_mode='auto'
camera.iso=0
##camera.exposure_mode='off'
##camera.shutter_speed=30000
##
##camera.awb_mode='off'
##camera.awb_gains=1
stream_done=False
sums=[]


def outputs():
    global frame
    stream = io.BytesIO()
    while not stream_done:
        
        yield stream
        start=timer()
        stream.seek(0)
        #frame=cv2.imdecode(np.fromstring(stream.getvalue(),dtype=np.uint8),1)
        frame=np.fromstring(stream.getvalue(),dtype=np.uint8,count=fw*fh).\
               reshape((fh,fw))
        #frame=stream.getvalue()
        
        stream.seek(0)
        stream.truncate()
        end=timer()
        print(end-start)
def capt():
    camera.capture_sequence(outputs(),format='yuv', use_video_port=True)


def startcapt():
    global t
    t = Thread(target=capt, args=())
    t.daemon = True
    t.start()
    sleep(0.5)
    



#start=timer()
startcapt()

while cv2.waitKey(1) != ord("q") and stream_done==False:
#    src=np.fromstring(frame,dtype=np.uint8).\
#         reshape((fh,fw,3))[:h,:w,:]
    cv2.imshow("detection", frame)

#while(timer()-start)<50:
#    sleep(5)

stream_done=True
sleep(0.5)
camera.close()
t.join()    
cv2.destroyAllWindows()
print len(sums)
print "quit"
