Saving a Video using OpenCV in python

Saving a Video using OpenCV in python

Saving a video using OpenCV in Python involves capturing frames from a video source, processing them (if required), and then writing those frames to an output video file. Here's a step-by-step guide:

  1. Install OpenCV:

    If you haven't already, you can install OpenCV using pip:

    pip install opencv-python 
  2. Capture and Save Video:

    Here's a simple script to capture video from your webcam and save it:

    import cv2 # Specify the video source. 0 usually refers to the built-in webcam. cap = cv2.VideoCapture(0) # Define the codec and create a VideoWriter object to save the video # Arguments for VideoWriter: # - output filename # - codec # - frames per second # - frame size fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4)))) while(cap.isOpened()): ret, frame = cap.read() if ret: # (Optional) Process the frame here. For example, convert to grayscale: # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # out.write(gray) # Write the frame to the output video out.write(frame) cv2.imshow('Video Stream', frame) # Break the loop when 'q' key is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break else: break # Release resources cap.release() out.release() cv2.destroyAllWindows() 

    This script captures video from the default camera (index 0) and saves it to output.avi. If you want to save in a different format, like MP4, you'd change the filename's extension and the fourcc codec.

  3. Note on Codecs:

    The choice of codec (fourcc) might depend on your OS and the file format you want to write. For example:

    • 'XVID' is commonly used for AVI files.
    • For MP4 files, you might use 'mp4v' on macOS or 'MJPG', 'H264', 'AVC1', etc., on Windows/Linux.

    Ensure that the chosen codec is compatible with the file extension and is installed on your machine.

That's the basic way to capture and save a video using OpenCV in Python. You can also introduce various processing steps before saving the frame to create effects or analyze the video content.


More Tags

ilmerge warnings obiee find-occurrences custom-element quickblox onchange ipywidgets dispatch httpwebresponse

More Programming Guides

Other Guides

More Programming Examples