import io
import time
import threading
import picamera
import numpy
import cv2
from timeit import default_timer as timer
# Create a pool of image processors
done = False
lock = threading.Lock()
pool = []
sums=[]
w=1280
h=720
fw=(w+31)//32*32
fh=(h+15)//16*16
cv2.namedWindow("fuckyou", cv2.WINDOW_AUTOSIZE)

class ImageProcessor(threading.Thread):
    def __init__(self):
        super(ImageProcessor, self).__init__()
        self.stream = io.BytesIO()
        self.event = threading.Event()
        self.terminated = False
        self.start()

    def run(self):
        # This method runs in a separate thread
        global done
        global sums
        while not self.terminated:
            # Wait for an image to be written to the stream
            if self.event.wait(1):
                try:
                    self.stream.seek(0)
                    
                    #dat=numpy.fromstring(self.stream.getvalue(),dtype=numpy.uint8)
                    Y=numpy.fromstring(self.stream.getvalue(),dtype=numpy.uint8,count=fw*fh).\
                       reshape((fh,fw))
                    #sums.append(cv2.imdecode(dat,1))
                    sums.append(Y)

                    
                    #done=True
                finally:
                    # Reset the stream and event
                    self.stream.seek(0)
                    self.stream.truncate()
                    self.event.clear()
                    # Return ourselves to the pool
                    with lock:
                        pool.append(self)

def streams():
    while (timer()-start)<10:
        with lock:
            if pool:
                processor = pool.pop()
            else:
                processor = None
        if processor:
            yield processor.stream
            processor.event.set()
        else:
            # When the pool is starved, wait a while for it to refill
            time.sleep(0.1)

with picamera.PiCamera() as camera:
    pool = [ImageProcessor() for i in range(4)]
    camera.resolution = (w, h)
    camera.framerate = 40
    camera.exposure_mode='off'
    camera.awb_mode='off'
    camera.shutter_speed=30000
    camera.awb_gains=1
    start=timer()
    camera.capture_sequence(streams(),format='yuv', use_video_port=True)

print len(sums)
##while cv2.waitKey(1) != ord("q"):
##    for i in sums:
##        cv2.imshow("fuckyou",i)
##        cv2.waitKey(1)
    

print(timer()-start)
# Shut down the processors in an orderly fashion
while pool:
    with lock:
        processor = pool.pop()
    processor.terminated = True
    processor.join()
