# importing the modules
import cv2 #to capture images
import math, operator #for rms calculation
from PIL import Image, ImageChops
import time #to monitor the time between images
import os #to write/delete files

# image capture initialisation
cam = cv2.VideoCapture(0)
cv2.namedWindow("test")
img_counter = 0

while True:
    # to show the frame while the recording is going on
    ret, frame = cam.read()
    cv2.imshow("test", frame)
    if not ret:
        break
    k = cv2.waitKey(1)

    # to terminate the program when escape is pressed
    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break
    else:
        # to capture 2 images 5 seconds apart
        # and the next image immediately after the second image (loop iteration 2)
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_name))
        img_counter += 1
        time.sleep(5)   # delay only if image is captured
    
    
    
    ret, frame = cam.read()
    cv2.imshow("test", frame)
    if not ret:
        break
    k = cv2.waitKey(1)

    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break
    else:
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_name))
        img_counter += 1
        # no delay this this time so that we can capture the next two images quickly
    
    
    if img_counter == 2:
        # creating a image1 object
        im1 = Image.open(r"/Users/sharatgoyal/Desktop/SchoolWork/opencv_frame_0.png") #pathname to image can be obtained with right click on image+Option+Copy File as Pathname
        # creating a image2 object
        im2 = Image.open(r"/Users/sharatgoyal/Desktop/SchoolWork/opencv_frame_1.png")
        "Calculate the root-mean-square difference between two images"
        diff = ImageChops.difference(im1, im2)
        h = diff.histogram()
        sq = (value*((idx%256)**2) for idx, value in enumerate(h))
        sum_of_squares = sum(sq)
        rms = math.sqrt(sum_of_squares/float(im1.size[0] * im1.size[1])) #rms formula
        print(rms)
         # to delete the used images
        os.remove(r"/Users/sharatgoyal/Desktop/SchoolWork/opencv_frame_0.png")
        os.remove(r"/Users/sharatgoyal/Desktop/SchoolWork/opencv_frame_1.png")
        img_counter = 0


# to end the recording
cam.release()
cv2.destroyAllWindows()
