Recording Webcam Video in OpenCV Python

Understanding Webcam Video Recording

OpenCV provides functions to access the webcam and save video. This allows real-time video capture and recording.

Recording Video from Webcam

Step-by-Step Explanation with Code:

import cv2

Import the OpenCV library.

cap = cv2.VideoCapture(0)

Initialize the webcam. The argument 0 refers to the default webcam, while 1 can be used for an external camera.

fourcc = cv2.VideoWriter_fourcc(*'XVID')

Define the codec for video encoding. This codec is commonly used for AVI files.

out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

Create a video writer object to save the recorded video. The parameters define the filename, codec, frames per second, and frame size.

while cap.isOpened():

Start a loop to read and process each frame while the camera is open.

ret, frame = cap.read()

Read a frame from the webcam. If the frame is successfully captured, ret will be true.

if not ret:
    break

Exit the loop if the frame is not captured correctly.

out.write(frame)

Save the current frame to the video file.

cv2.imshow('Webcam Recording', frame)

Display the captured frame in a window.

if cv2.waitKey(1) & 0xFF == ord('q'):
    break

Wait for 1 millisecond for a key press. If the ‘q’ key is pressed, exit the loop.

cap.release()
out.release()
cv2.destroyAllWindows()

Release the webcam and video writer resources, then close all OpenCV windows.

complete code:

import cv2

cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    out.write(frame)
    cv2.imshow('Webcam Recording', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

Expected Output:

  1. A live video feed window labeled “Webcam Recording” displaying real-time webcam footage.
  2. The video is being recorded and saved as “output.avi” in the current directory.
  3. The recording stops when the ‘q’ key is pressed.
  4. Once stopped, the “output.avi” file can be played using a media player that supports AVI format.

 

Leave a Comment

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

Scroll to Top