import numpy as np
import cv2

# http://docs.opencv.org/master/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a&gsc.tab=0
##http://docs.opencv.org/master/d4/d73/tutorial_py_contours_begin.html#gsc.tab=0

#cap = cv2.VideoCapture('videoRest.mp4') #Open video file
cap = cv2.VideoCapture('Estavel.mp4') #Open video file
#fgbg = cv2.createBackgroundSubtractorMOG2(history=200, varThreshold=16, detectShadows=True)
fgbg = cv2.createBackgroundSubtractorMOG2(history=200, varThreshold=255, detectShadows=True) #Create the background substractor
kernelOp = np.ones((3,3),np.uint8)
kernelCl = np.ones((11,11),np.uint8)

while(cap.isOpened()):
	ret, frame = cap.read() #read a frame

	fgmask = fgbg.apply(frame) #Use the substractor
	try:
		#threshold: If pixel value is greater than a threshold value, it is assigned one value (may be white), else it is assigned another value (may be black).First argument is the source image, which should be a grayscale image. Second argument is the threshold value which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given if pixel value is more than (sometimes less than) the threshold value. OpenCV provides different styles of thresholding and it is decided by the fourth parameter of the function.
		#ver http://docs.opencv.org/trunk/d7/d4d/tutorial_py_thresholding.html
		#ret,imBin= cv2.threshold(fgmask,200,255,cv2.THRESH_BINARY)
		#ACHA CONTORNOS GERAL OPC2
		#imBin = cv2.adaptiveThreshold(fgmask,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
            #cv2.THRESH_BINARY_INV,11,2)
		#ACHA CONTORNOS EM GERAL
		imBin = cv2.adaptiveThreshold(fgmask,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY_INV,11,2)
		#imBin = cv2.Canny(fgmask, 100, 200)
		#ret,imBin= cv2.threshold(fgmask,200,255,cv2.THRESH_TOZERO)
		#ret,imBin= cv2.threshold(fgmask,200,255,cv2.THRESH_TRUNC)
		#Opening (erode->dilate) para tirar ruido
		mask = cv2.morphologyEx(imBin, cv2.MORPH_OPEN, kernelOp)
		#Closing (dilate -> erode) para juntar regioes brancas
		mask = cv2.morphologyEx(mask , cv2.MORPH_CLOSE, kernelCl)
	except:
	#if there are no more frames to show...
		print('EOF')
		break

	_, contours0, hierarchy = cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
	for cnt in contours0:
		cv2.drawContours(frame, cnt, -1, (0,255,0), 3, 8)

		cv2.imshow('Frame',frame)

	#Abort and exit with 'Q' or ESC
	k = cv2.waitKey(30) & 0xff
	if k == 27:
		break

cap.release() #release video file
cv2.destroyAllWindows() #close all openCV windows