#!/usr/bin/python
import sys
import cv2
import random

# structure
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,4))

# input
input_file = sys.argv[1]
capture = cv2.VideoCapture(input_file)
if not capture.isOpened():
    raise Exception("cannot open file " + input_file)

# basic parameters
frameWidth  = capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
frameHeight = capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
fps         = capture.get(cv2.cv.CV_CAP_PROP_FPS)

# first read
flag,frame = capture.read()
current    = cv2.blur(frame, (5,5))

# main loop
i=0
while True:
    i+=1
    # get frame
    flag,frame = capture.read()
    if not flag:
        break

    # compute difference of two consecutive frames
    previous   = current
    current    = cv2.blur(frame, (5,5))
    if previous is None:
        previous = current
    difference = cv2.absdiff(current, previous)

    # compute historgram - how many elements differ, in fact
    frame2 = cv2.cvtColor(difference, cv2.cv.CV_RGB2GRAY)
    retval,thresh = cv2.threshold(frame2, 20, 0xFF, cv2.THRESH_BINARY)
    #retval,thresh = cv2.adaptiveThreshold(frame2, 0xFF, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 1)
    erode1 = cv2.erode(thresh, es)
    hist = cv2.calcHist( [erode1], [0], None, [2], [0, 256] )

    # output if movement has been detected
    p = hist[1]/(hist[1]+hist[0])
    if p > 1/1000.0:
        print("MOVEMENT DETECTED AT: " + str(p) + " @ " + str(i/fps) + "[s]")
