import cv2
import numpy as np
import os
#from picamera.array import PiRGBArray
#from picamera import PiCamera
import time


###################################################################################################
def nothing(x):
    pass

def main():
    resolution=(576,512)
    framerate=30
    iso=800
    gain=1.15
    camera = PiCamera()
    camera.resolution = resolution
    camera.framerate = framerate
    camera.iso=iso
    camera.exposure_mode='off'
    camera.awb_mode='off'
    camera.awb_gains=gain
    time.sleep(2.0)
    rawCapture = PiRGBArray(camera, size=resolution)
    stream = camera.capture_continuous(rawCapture,
            format="bgr", use_video_port=True)

   
    frame = None
    
    
    cv2.namedWindow("gray", cv2.WINDOW_AUTOSIZE)        
    cv2.namedWindow("detection", cv2.WINDOW_AUTOSIZE)

    cv2.createTrackbar('param1','detection',120,255,nothing)
    cv2.createTrackbar('param2','detection',50,255,nothing)
    cv2.createTrackbar('blur','detection',1,255,nothing)
    cv2.createTrackbar('gain','detection',1,500,nothing)
    cv2.createTrackbar('iso','detection',100,800,nothing)
    cv2.createTrackbar('speed','detection',30000,100000,nothing)      


    for (i,f) in enumerate(stream):
        gain=cv2.getTrackbarPos('gain','detection')
        iso=cv2.getTrackbarPos('iso','detection')
        speed=cv2.getTrackbarPos('speed','detection')
        p1=cv2.getTrackbarPos('param1','detection')
        p2=cv2.getTrackbarPos('param2','detection')
        accu=cv2.getTrackbarPos('accu','detection')
        blur=cv2.getTrackbarPos('blur','detection')
        minR=cv2.getTrackbarPos('minR','detection')
        maxR=cv2.getTrackbarPos('maxR','detection')
        camera.iso=iso
        camera.awb_gains=gain/100.0
        camera.shutter_speed=speed
        # grab the frame from the stream and clear the stream in
        # preparation for the next frame
        frame = f.array
        rawCapture.truncate(0)
        # if the thread indicator variable is set, stop the thread
        # and resource camera resources
        if  cv2.waitKey(1) == ord("q"):
            stream.close()
            rawCapture.close()
            camera.close()
            cv2.destroyAllWindows()
            print "quit"
            break

            
        grau = cv2.medianBlur(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY),blur*2+1)
        imgCanny = cv2.Canny(grau, p2, p1,L2gradient=False)   # get Canny edges


        cv2.imshow("gray", grau)
        cv2.imshow("detection", imgCanny)
        
    # end while
    cv2.imwrite('Cannypic.jpeg',imgCanny,[cv2.IMWRITE_JPEG_QUALITY,100])
    cv2.destroyAllWindows()                 # remove windows from memory


    return

###################################################################################################
if __name__ == "__main__":
    main()
