import numpy as np
import argparse
import cv2
from picamera.array import PiRGBArray
from picamera import PiCamera
import picamera
from time import sleep
from fractions import Fraction
import os
import datetime
now=datetime.datetime.now()
first=(60*now.minute+now.second)*1000000+now.microsecond
os.system("sudo bash -c \"echo none > /sys/class/leds/led0/trigger\"")
os.system("sudo bash -c \"echo 0 > /sys/class/leds/led0/brightness\"")
os.system("sudo bash -c \"echo none > /sys/class/leds/led1/trigger\"")
os.system("sudo bash -c \"echo 0 > /sys/class/leds/led1/brightness\"")

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
#ap.add_argument("-i", "--image", help = "path to the image file")
ap.add_argument("-r", "--radius",default=41, type = int,
	help = "radius of Gaussian blur; must be odd")
args = vars(ap.parse_args())
# initialize the camera and grab a reference to the raw camera capture
camera=PiCamera()
camera.resolution=(3280,2464)
#camera.resolution=(640,480)
#camera.sensor_mode=7
#camera.vflip=True
camera.CAPTURE_TIMEOUT=120
expose=False
#########LOW LIGHT CONDITION
if expose:
    p=6
    h=8
    k=6
    camera.framerate=Fraction(1, p)
    camera.shutter_speed = 1000000*k
    camera.exposure_mode = 'off'
    camera.iso = 100*h
##############

print 'config set'
sleep(10)
for shot in range(14):
    rawCapture = PiRGBArray(camera) 
    # load the image and convert it to grayscale
    #image = cv2.imread(args["image"])
    print 'config done. capturing....'
    camera.capture(rawCapture, format="bgr")
    print 'capturing done, proceccing'
    image = rawCapture.array
    orig = image.copy()
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # apply a Gaussian blur to the image then find the brightest
    # region
    gray = cv2.GaussianBlur(gray, (args["radius"], args["radius"]), 0)
    (minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(gray)
    image = orig.copy()
    cv2.circle(image, maxLoc, args["radius"], (255, 0, 0), 2)
    print 'writing...'
    cv2.imwrite('1_%d.tiff'%shot,orig) 
    cv2.imwrite('1_%d.png'%shot,orig,[cv2.IMWRITE_PNG_COMPRESSION,0])
    cv2.imwrite('1_%d.jpeg'%shot,orig,[cv2.IMWRITE_JPEG_QUALITY,100])
    cv2.imwrite('1_%d_detected.jpeg'%shot,image,[cv2.IMWRITE_JPEG_QUALITY,100])
    # display the results of our newly improved method
    #cv2.imshow("Robust detection", image)
os.system("sudo bash -c \"echo cpu0 > /sys/class/leds/led0/trigger\"")
os.system("sudo bash -c \"echo 1 > /sys/class/leds/led0/brightness\"")
os.system("sudo bash -c \"echo input > /sys/class/leds/led1/trigger\"")
os.system("sudo bash -c \"echo 1 > /sys/class/leds/led1/brightness\"")
now=datetime.datetime.now()
last=(60*now.minute+now.second)*1000000+now.microsecond

print (last-first)/1000
cv2.waitKey(0)
