import numpy as np

import cv2, sys

import time

cap = cv2.VideoCapture(0)
time.sleep(1.75)


#this is how you set the correct resolution for the camera. default is 640x480
#ret = cap.set(3,1280)
#ret = cap.set(4,720)

#ret = cap.set(3,320)
#ret = cap.set(4,180)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'H264')

#settings for the video file that will be written to
#with the out.write(frame) command 
#out = cv2.VideoWriter(r'/home/pi/Desktop/VideoFileFolderTest/stream1.mp4',fourcc, 20.0, (320,180))
#out = cv2.VideoWriter('video5.avi',fourcc, 20.0, (1280,720))

#/var/www/html/stream.mp4
#r"C:\Users\Josh\Desktop\video.avi"

#out = cv2.VideoWriter('/home/pi/Desktop/VideoFileFolderTest/test.mp4',fourcc, 10.0, (640,480))
out = cv2.VideoWriter('/var/www/html/stream.mp4',fourcc, 10.0, (640,480))


backgroundMask = cv2.createBackgroundSubtractorMOG2()
font = cv2.FONT_HERSHEY_SIMPLEX

# Set threshold and maxValue for the threshholding function
thresh = 1
maxValue = 255



# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

params.filterByColor = True
params.blobColor = 255

# Change thresholds
params.minThreshold = 1
params.maxThreshold = 720
 
# Filter by Area.
params.filterByArea = True
params.minArea = 50
params.maxArea = 250000

 
# Filter by Circularity
params.filterByCircularity = False
params.minCircularity = 0.1
 
# Filter by Convexity
params.filterByConvexity = False
params.minConvexity = 0.87
 
# Filter by Inertia
params.filterByInertia = False
params.minInertiaRatio = 0.01

detector = cv2.SimpleBlobDetector_create(params)


# Set up the detector with default parameters.
# detector = cv2.SimpleBlobDetector_create()



while(1):


    ret, frame = cap.read()
    sys.stdout.write( frame.tostring() )
   
    if ret==True:
        bgMask = backgroundMask.apply(frame)



 
# binary threshhold sets everything above the threshold to the max value everything else 0
        th, threshedBGMask = cv2.threshold(bgMask, thresh, maxValue, cv2.THRESH_BINARY);



# Detect blobs.
        keypoints = detector.detect(threshedBGMask)

# 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
        circledActionsFrame = cv2.drawKeypoints(frame, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
        circledActionsMask = cv2.drawKeypoints(threshedBGMask, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)





#shows filtered frame
        cv2.imshow('tbgmask',circledActionsMask)


# take the picture, treat it as greayscale, none masks, 256 bins, with a range of 0-256
#        hist = cv2.calcHist(fgmask,[0],None,[8],[0,256])

# property id "5" is frames per second from the camera, not drawn frames

#        framesPerSecond = cap.get(5)
        cv2.putText(circledActionsFrame ,str(len(keypoints)),(10,310), font, 4,(255,255,255),2,cv2.LINE_AA)
#        cv2.putText(circledActionsFrame ,str(framesPerSecond),(10,100), font, 4,(255,255,255),2,cv2.LINE_AA)
#shows original frame
        cv2.imshow('frame',circledActionsFrame)



        if (len(keypoints)) >= 1 :
            out.write(frame)



#scan filtered framefor clusters



#escape key to exit
        k = cv2.waitKey(30) & 0xff

        if k == 27:

            break


    
cap.release()
out.release()
cv2.destroyAllWindows()
