Life2Coding
Save Webcam Video Feed to a File using OpenCV in Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3

Goals:

In this tutorial, I will show you how to save webcam video output to a file along with fps value and output codec using OpenCV with Python coding.

Documentation:

Python: cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) → <VideoWriter object>

Python: cv2.VideoWriter.isOpened() → retval

Python: cv2.VideoWriter.open(filename, fourcc, fps, frameSize[, isColor]) → retval

Python: cv2.VideoWriter.write(image) → None

Write videos to a video file

Parameters:          

  • filename – Name of the output video file.
  • fourcc – 4-character code of codec used to compress the frames. List of codes can be obtained at Video Codecs by FOURCC page.
    • cv2.VideoWriter_fourcc(c1, c2, c3, c4) → retval
    • Examples:
    • cv2.VideoWriter_fourcc(*’MP4V’)
    • cv2.VideoWriter_fourcc(*’MJPG’)
    • cv2.VideoWriter_fourcc(*’XVID’)
    • cv2.VideoWriter_fourcc(*’DIVX’)
    • cv2.VideoWriter_fourcc(*’X264′)
  • fps – Framerate of the created video stream.
  • frameSize – Size of the video frames.
  • isColor – If it is not zero, the encoder will expect and encode color frames, otherwise it will work with grayscale frames (the flag is currently supported on Windows only).

Steps:

  • Initialize webcam feed using cv2.VideoCapture()
  • Read webcam images using cv2.VideoCapture.read()
  • Initialize webcam video writer using cv2.VideoWriter()
  • Save video frame by frame to a file using cv2.VideoWriter.write()
  • Display each image using cv2.imshow()
  • Wait for keyboard button press using cv2.waitKey()
  • Release the VideoCapture and VideoWriter using cv2.VideoCapture.release() and cv2.VideoWriter.release()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2

def save_webcam(outPath,fps,mirror=False):
    # Capturing video from webcam:
    cap = cv2.VideoCapture(0)

    currentFrame = 0

    # Get current width of frame
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)  # float
    # Get current height of frame
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)  # float

    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*"XVID")
    out = cv2.VideoWriter(outPath, fourcc, fps, (int(width), int(height)))

    while (cap.isOpened()):

        # Capture frame-by-frame
        ret, frame = cap.read()

        if ret == True:
            if mirror == True:
                # Mirror the output video frame
                frame = cv2.flip(frame, 1)
            # Saves for video
            out.write(frame)

            # Display the resulting frame
            cv2.imshow('frame', frame)
        else:
            break

        if cv2.waitKey(1) & 0xFF == ord('q'):  # if 'q' is pressed then quit
            break

        # To stop duplicate images
        currentFrame += 1

    # When everything done, release the capture
    cap.release()
    out.release()
    cv2.destroyAllWindows()

def main():
    save_webcam('output.avi', 30.0,mirror=True)

if __name__ == '__main__':
    main()

Output:

save-webcam-video-263x250 Save Webcam Video Feed to a File using OpenCV in Python

life2coding_icon [] Save Webcam Video Feed to a File using OpenCV in Python

One thought on “Save Webcam Video Feed to a File using OpenCV in Python

  1. raam

    Thanks for sharing ur valuable knowledge sir! do you have any idea about re-opening the out.release().
    for ex: I am interfacing 2switches to stop and to start record, once I pressed sw1 it should start recording and when I pressed sw2 it should stop recording(both are working fine). the problem is when I press sw1 again the start recording should run, but it is not recording. the reason is that while stop recording we closed out.release(). we have to re-initialize out.release() so how can i re-open out.release() function again to start recording.
    please do help me I am a beginner to python struggling from last month.

    your help will be greatly appreciated!

    thank you
    Ramesh.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.