# import the necessary packages
import numpy as np;
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2

resolution = (320, 240)

# control detector parameters
params = cv2.SimpleBlobDetector_Params()

# params.minThreshold = 10
# params.maxThreshold = 200

params.filterByColor = True
params.filterByCircularity = False
params.filterByArea = True
params.filterByConvexity = False
params.filterByInertia = False
params.filterByCircularity = False

params.minArea = 1000
params.maxArea = 9999

params.blobColor = 0

print ("OpenCV Version: ", cv2.__version__)

# check opencv version and construct the detector
is_v2 = cv2.__version__.startswith("2.")
if is_v2:
    detector = cv2.SimpleBlobDetector(params)
else:
    detector = cv2.SimpleBlobDetector_create(params)

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = resolution
rawCapture = PiRGBArray(camera, size=resolution)

# allow the camera to warmup
time.sleep(0.1)

once = True

while True:
    # grab an image from the camera
    camera.capture(rawCapture, format="bgr")
    image = rawCapture.array

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    # edged = cv2.Canny(blurred, 75, 200)

    thr = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 121, 2)
	
    if once:
        print("Image shape: ",thr.shape)

    # im2, contours, hierarchy = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    im2, contours, hierarchy = cv2.findContours(thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS) #, cv2.Point(0, 0))
    im3 = cv2.drawContours(image, contours, -1, (255,0,0), 3)
    cv2.imshow("Contours Image",im3)
	
    # Detect blobs.
    keypoints = detector.detect(thr)

    if once:
        print("keypoints", keypoints)

    # Draw detected blobs as red circles.
    # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob
    im_with_keypoints = cv2.drawKeypoints(thr, keypoints, np.array([]), (0, 0, 255),
                                          cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

    rawCapture.truncate(0)
    # display the image on screen and wait for a keypress
    # cv2.imshow("Camera Image", image)
    # cv2.imshow("Greyscale Image",gray)
    # cv2.imshow("Blurred Image",blurred)
    # cv2.imshow("Edged Image",edged)
    # cv2.imshow("thresholded image", thr)
    cv2.imshow("Image_with_Keypoints", im_with_keypoints)
    key = cv2.waitKey(1)
    if key == ord("q"):
        print("quit requested by keyboard input")
        break
    once = False
