##from time import sleep
##import numpy as np
##import cv2
##from imutils.video.pivideostream import PiVideoStream
##
##def nothing(x):
##    pass
##
##vs=PiVideoStream((720,720),40)
##d=cv2.CV_16S
##vs.start()
##sleep(2)
##cv2.namedWindow("detection", cv2.WINDOW_AUTOSIZE)
##cv2.createTrackbar('time','detection',10,100,nothing)
##prev=0
##while cv2.waitKey(1) != ord("q"):
##    time=cv2.getTrackbarPos('time','detection')/100.0
##    sleep(time)
##    cv2.imshow('detection',vs.read())
##    now=cv2.sumElems(vs.read())[0]
##    print(prev==now)
##    prev=now
##    
##
##cv2.destroyAllWindows()
##vs.stop()
##print "exit"





##sharp=[]
##for i in range(100,-5,-5):
##    sharp.append([i*100,i])
##
##sharp[2/2][0]=sharp[2/2][0]+1000
##print sharp
##print sharp[1][0]
##a,b=max(sharp)
##
##print a,b

##center=3
##steps=[(x+center) for x in range(-6,6,1) if (x+center)>=0 and (x+center)<=100]
##print steps[len(steps)-2::-1]
##print len(steps)


from time import sleep
import numpy as np
import cv2
from imutils.video.pivideostream import PiVideoStream
from sys import exit
from multiprocessing.dummy import Pool
from timeit import default_timer as timer

def findsharpness(src):
    src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    #cv2.imshow('detection',src)
    src=cv2.bilateralFilter(src,3,6,1.5)
    dx = cv2.convertScaleAbs(cv2.Sobel(src, cv2.CV_16S,1,0, ksize=3))
    dy = cv2.convertScaleAbs(cv2.Sobel(src, cv2.CV_16S,0,1, ksize=3))
    accu=cv2.addWeighted(dx,0.5,dy,0.5,0,-1)
    #cv2.imshow('detection',accu)
    return cv2.sumElems(accu)[0]
    

def slicer(src):
    size=src.shape[0:2:1]
    return (src[0:size[0]/2,0:size[1]/2],
            src[0:size[0]/2,size[1]/2:size[1]],
            src[size[0]/2:size[0],0:size[1]/2],
            src[size[0]/2:size[0],size[1]/2:size[1]])


p=Pool(processes=4)
cv2.namedWindow("detection", cv2.WINDOW_AUTOSIZE)


    
if __name__ == '__main__':
    print("[INFO] sampling THREADED frames from `picamera` module...")
    vs = PiVideoStream((720,720),30)
    #vs.roi((0.3,0.24,0.55,0.55))
    vs.start()
    sleep(2)
    
    while cv2.waitKey(1)!=ord("q"):
        start=timer()
        #sum([i for i in p.map(findsharpness,[item for sublist in map(slicer,slicer(src)) for item in sublist],1) if i is not None])
        sum([i for i in p.map(findsharpness,slicer(vs.read()),1) if i is not None])
        #print p.map(findsharpness,slicer(src))
        
        end=timer()
        print end-start
##        result= p.map(findsharpness,(slicer(vs.read())),chunksize=1)
##        print result
        
        


    vs.stop()
    p.close()
    p.join()
    print "exit"
    exit()
