#!/usr/bin/env
import numpy as np
import cv2, csv, os, re
import argparse
import warnings


'''

use this python script to track fish in mate choice tanks with gravel
it uses a subtraction algorithm to identify the fish, and refreshes the 'background' every 150 frames, which turns out to be useful

usage example: python differenceImageGravel.py -i /Users/lukereding/Desktop/video.mp4

the results will be written to a .csv file in the same directory that you run the script from

things you might need to change:
-- the mask bounds 
-- the minimum contour size
-- the contour aspect ratio

The script assumes your video are of size 1280x720
'''

print "\n\ndifferenceImageGravel.py\n"

# initialize some constants, lists, csv writer
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--inputVideo", help = "path to the video")
args = vars(ap.parse_args())
lower = np.array([0,0,0])
upper = np.array([255,255,20])
counter = 0

# set up the video capture to the video that was the argument to the script
cap = cv2.VideoCapture(args["inputVideo"])

# output to csv file where the results will be written
name = re.split('[/.]', args["inputVideo"], flags=re.IGNORECASE)[-2]
name = name + ".csv"
print "name of csv file: " + str(name)

myfile = open(name,'wb')
csv_writer = csv.writer(myfile, quoting=csv.QUOTE_NONE)
csv_writer.writerow(("x","y","frame"))

# test to make sure the video dimensions are the right size
_,test = cap.read()
if test.shape[0] != 720:
	print "*************\nnote that this script is meant for videos that are 1280x720 pixels. It looks like your video isn't. You can either re-scale using ffmpeg or alter this code (espeically the masking step)\n********"


######################
# declare some functions:####
#####################################

# converts a frame to HSV, blurs it, masks it to only get the tank by itself
def convertToHSV(frame):
	blurred = cv2.blur(frame,(7,7))
	hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
	mask = np.zeros((720, 1280, 3),np.uint8)
	mask[150:600,150:1170] = hsv[150:600,150:1170]
	return mask


# function to determine where the fish started in the video
def findStartingPoint(video,numberOfFrames):
	# the function will go numberOfFrames frames ahead in the video and do a subtraction
	# the hope is that the fish will have moved at some point during this time
	count = 0
	# I don't know a better way to jump ahead so many frames
	while count <= numberOfFrames:
		# read in the frame for each tick of the loop
		ret,frame = video.read()
		# grab a frame from the middle. Assume the screens have turned on by then
		if count == numberOfFrames/2:
			hsv_middle = convertToHSV(frame)
		if count == numberOfFrames:
			# grab the last frame in the numberOfFrames window
			hsv_end = convertToHSV(frame)