"""
*************************************************************************
// Example program using OpenCV library
//      python >3.7 - OpenCV 4.5
// @file	e2b.py
// @author Luis M. Jimenez
// @date 2022
//
// @brief Course: Computer Vision (1782)
// Dept. of Systems Engineering and Automation
// Automation, Robotics and Computer Vision Lab (ARVC)
// http://arvc.umh.es
// University Miguel Hernandez
//
// @note Description:
//	- This example captures images from a video file,
//	- Extracts borders
//	- Stores the result in a new video file
//
*************************************************************************
"""

# Import libraries
import cv2 as cv
import numpy as np
import argparse

# -----------------------------------------
# Global variables
# -----------------------------------------

WINDOW_CAMERA1 = '(W1) Video'           # window id
WINDOW_BORDERS = '(W2) Canny Borders'   # window id
VIDEO_FILE = 'video.mp4'                # default video file

# check command line parameters (videoFile)
parser = argparse.ArgumentParser(description='OpenCV example: image file processing')
parser.add_argument('videoFile', nargs='?', default=VIDEO_FILE,  help='video file')
VIDEO_FILE = parser.parse_args().videoFile

# -----------------------------------------
# Put here the code to Initialize objets
# -----------------------------------------

# Open input video object
inputVideo = cv.VideoCapture(VIDEO_FILE)
if not inputVideo.isOpened():
    print("I cannot open {VIDEO_FILE} video file, sorry.")
    exit()

# Getting video resolution / FPS
cameraWidth = int(inputVideo.get(cv.CAP_PROP_FRAME_WIDTH))
cameraHeight = int(inputVideo.get(cv.CAP_PROP_FRAME_HEIGHT))
fps = inputVideo.get(cv.CAP_PROP_FPS)

# Open output video object
outputVideo = cv.VideoWriter("result.avi",  cv.VideoWriter.fourcc('D', 'I', 'V', 'X'),
                                fps, (cameraWidth, cameraHeight), False)
if not outputVideo.isOpened():
    print("I cannot open the video output file, sorry.")
    exit()


# Creating visualization windows
cv.namedWindow(WINDOW_CAMERA1, cv.WINDOW_AUTOSIZE)
cv.namedWindow(WINDOW_BORDERS, cv.WINDOW_AUTOSIZE)

print(f"Capturing images from video {VIDEO_FILE} ({cameraWidth},{cameraHeight}) {fps=}")
print("...Hit q/Q/Esc to exit.")


# -----------------------------------------
# Main Loop
# while there are images ...
# -----------------------------------------
while True:
    # Capture frame-by-frame
    ret, capture = inputVideo.read()

    # if frame is read correctly ret is True
    if not ret:
        print("Stream ended. Exiting ...")
        break
    # -----------------------------------------
    # Put your image processing code here
    # -----------------------------------------

    #  transform to gray level
    gray_image = cv.cvtColor(capture, cv.COLOR_BGR2GRAY);

    # Apply filter to image
    borders_image = cv.Canny(gray_image, threshold1=80, threshold2=150)     # Canny border detector

    # writes image to video  file
    outputVideo.write(borders_image)

    # -----------------------------------------
    # Put your visualization code here
    # -----------------------------------------
    cv.imshow(WINDOW_CAMERA1, capture)     # Display the resulting frame
    cv.imshow(WINDOW_BORDERS, borders_image)  # Display the resulting frame

    # check keystroke to exit (image window must be on focus)
    key = cv.pollKey()
    if key == ord('q') or key == ord('Q') or key == 27:
        break

# End while (main loop)

# -----------------------------------------
# free windows and video resources
# -----------------------------------------
cv.destroyAllWindows()
if inputVideo.isOpened():  inputVideo.release()
if outputVideo.isOpened():  outputVideo.release()