#!/usr/bin/env python3
"""capture_frame.py : capture a single camera image and save in a file
"""
import argparse
import numpy as np
import cv2 as cv

#================================================================
def read_one_frame(capture, args):
    """Wait for the first available frame from a camera."""
    while True:
        success, frame = capture.read()
        if success:
            if args.verbose:
                print("read image of shape %s" % (str(frame.shape)))
            return frame

        # leave the while loop
        break

#================================================================
if __name__ == "__main__":
    parser = argparse.ArgumentParser( description = "Open a camera and save a single video frame.")
    parser.add_argument('--camera', default=0, type=int, help="Select camera by number (default: %(default)s).")
    parser.add_argument('--verbose', action='store_true', help='Enable more detailed diagnostic output.' )
    parser.add_argument('out', default="frame.png", type=str, nargs='?', help="Specify output imagefile name (default: %(default)s).")
    args = parser.parse_args()

    capture = cv.VideoCapture(args.camera)

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

    try:
        frame = read_one_frame(capture, args)

    except KeyboardInterrupt:
        print ("User quit.")
        capture.release()
        exit()

    # flip the image left to right for 'selfie' mode
    # frame = frame[:,::-1]

    # reduce image size and flip
    # frame = frame[::2,::-2]

    cv.imwrite(args.out, frame)
    print("wrote %s" % (args.out))

    capture.release()
