#!/usr/bin/env python3
"""process_sequence.py : process a series of images from an input video to output video
"""
import argparse, time
import numpy as np
import cv2 as cv

#================================================================
def open_video_output(frame, args, frame_rate=30):
    """Open a video output file sized for the given sample frame.  The frame is not written."""

    codec_code = cv.VideoWriter.fourcc(*'MJPG')  # motion JPEG
    frame_width = frame.shape[1]   # cols
    frame_height = frame.shape[0]  # rows
    return cv.VideoWriter(args.out, codec_code, frame_rate, (frame_width, frame_height))

#================================================================
if __name__ == "__main__":
    parser = argparse.ArgumentParser( description = "Process one video file to another.")
    parser.add_argument('-q','--quiet', action='store_true', help="Run without viewer window or console output.")
    parser.add_argument('--verbose', action='store_true', help='Enable even more detailed logging output.' )
    parser.add_argument('input', default="frames.avi", type=str, nargs='?', help="Specify input AVI file name (default: %(default)s).")
    parser.add_argument('out', default="processed.avi", type=str, nargs='?', help="Specify output AVI file name (default: %(default)s).")

    # various processing options follow
    parser.add_argument( '-s','--saturation', action='store_true', help='Use only saturation channel.')

    args = parser.parse_args()

    capture = cv.VideoCapture(args.input)

    if not capture.isOpened():
        print("Unable to open input file, exiting.")
        exit(1)

    if not args.quiet:
        cv.namedWindow("capture")

    # the output file will be created after the frame size is known
    output = None

    try:
        while True:
            success, frame = capture.read()
            if not success or frame is None:
                break

            if args.verbose:
                print("read image of shape %s" % (str(frame.shape)))

            # reduce the frame size by skipping pixels
            frame = frame[::2,::2]

            if args.saturation:
                # transform the image
                frame = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
                # pick out saturation and convert back to color image
                frame = frame[:,:,1]
                frame = cv.cvtColor(frame, cv.COLOR_GRAY2BGR)

            if not args.quiet:
                cv.imshow("capture", frame) # display the frame

            if output is None:
                output = open_video_output(frame, args)

            if output is not None:
                output.write(frame)
                if args.verbose:
                    print("wrote frame to file.")

            # If using the GUI, calling waitKey allows the window system event loop to run and update
            # the display.  The waitKey argument is in milliseconds.
            if not args.quiet:
                key = cv.waitKey(33) & 0xFF
                if key == ord('q'):
                    break

    except KeyboardInterrupt:
        print ("User quit.")

    output.release()
    capture.release()
