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:

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

Life2Coding

Technology Related Blog at Life2Coding
Feel free to contact us for your any kind of technical problems. We are here to help you.
life2coding_icon [] Save Webcam Video Feed to a File using OpenCV in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

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