Search code examples
pythonopencvvideo-capture

OpenCV Video capture using keyboard to start/stop


I have a running script capable of starting/stopping a video stream using 2 different keys;

  • Program runs and shows the live stream.
  • When ESC is hit, the program exits.
  • When SPACE is hit, the video stream is captured.

However, when a video is captured it stores all the stream from the beginning of script execution.

    import cv2
    import numpy as np

    capture = cv2.VideoCapture(1)
    codec = cv2.VideoWriter_fourcc(*'XVID')
    output = cv2.VideoWriter('CAPTURE.avi', codec, 30, (640, 480))

    while True:
        ret, frame_temp = capture.read()
        cv2.imshow('FRAME', frame_temp)
        key=cv2.waitKey(1)
        if key%256 == 27:
            break
        elif key%256 == 32:
            output.write(frame_temp)

    capture.release()
    output.release()
    cv2.destroyAllWindows()

So, instead when the program runs I would like;

  • Program runs and shows the live stream.
  • Begin recording the stream when SPACE is hit and stop the recording when SPACE is hit once more.

Any suggestions would be much appreciated.


Solution

  • You need an extra variable to figure out if you are recording. I made a variable called recording_flag

    import cv2
    import numpy as np
    
    capture = cv2.VideoCapture(1)
    codec = cv2.VideoWriter_fourcc(*'XVID')
    
    recording_flag = False
    
    while True:
        ret, frame_temp = capture.read()
        cv2.imshow('FRAME', frame_temp)
        key=cv2.waitKey(1)
        if key%256 == 27:
            break
        elif key%256 == 32:
            if recording_flag == False:
                # we are transitioning from not recording to recording
                output = cv2.VideoWriter('CAPTURE.avi', codec, 30, (640, 480))
                recording_flag = True
            else:
                # transitioning from recording to not recording
                recording_flag = False
    
        if recording_flag:
            output.write(frame_temp)
    
    capture.release()
    output.release()
    cv2.destroyAllWindows()