"""
*************************************************************************
// Example program using OpenCV library
//      python >3.7 - OpenCV 4.5
// @file	e2.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:
//  - Load, transform and save an image from a file
//  - file can be passed as parameter, if not
//      default image (building.jpg) is loaded from the same directory as script
//
*************************************************************************
"""

# Import libraries
import cv2 as cv
import numpy as np
import argparse

# -----------------------------------------
# Global variables
# -----------------------------------------

WINDOW_IMAGE = '(W1) Image'        # window id
WINDOW_BORDERS = '(W2) Canny Borders'   # window id
IMAGE_FILE = 'building.jpg'             # default image file

# check command line parameters (imageFile)
parser = argparse.ArgumentParser(description='OpenCV example: image file processing')
parser.add_argument('imageFile', nargs='?', default=IMAGE_FILE,  help='image file')
IMAGE_FILE = parser.parse_args().imageFile

# -----------------------------------------
# Put here the code to Initialize objets
# -----------------------------------------

# Open Image File
image = cv.imread(IMAGE_FILE)
if image is None:
    print(f"I can't open '{IMAGE_FILE}' file, sorry.")
    exit()

# Creating visualization windows
cv.namedWindow(WINDOW_IMAGE, cv.WINDOW_AUTOSIZE)
cv.namedWindow(WINDOW_BORDERS, cv.WINDOW_AUTOSIZE)

print("Processing image. Hit q/Q/Esc to exit.")

# -----------------------------------------
# Put your image processing code here
# -----------------------------------------

gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)    # transforms to gray level

borders_image = cv.Canny(gray_image, threshold1=80, threshold2=150)     # Canny border detector

cv.imwrite("result.jpg", borders_image)     # store result image

# -----------------------------------------
# Put your visualization code here
# -----------------------------------------
cv.imshow(WINDOW_IMAGE, image)     # Display the resulting frame
cv.imshow(WINDOW_BORDERS, borders_image)     # Display the resulting frame

# waits for keystroke to exit (image window must be on focus)
key = cv.waitKey(0)


# -----------------------------------------
# free windows and camera resources
# -----------------------------------------
cv.destroyAllWindows()
