0
0
Computer Visionml~5 mins

Video writing in Computer Vision

Choose your learning style9 modes available
Introduction
Video writing lets us save a series of images as a video file. This helps us keep and share moving pictures from our programs.
Saving frames from a camera to watch later
Creating a video from processed images or animations
Recording results of computer vision tasks like object tracking
Making time-lapse videos from photos
Saving output from simulations or games as videos
Syntax
Computer Vision
import cv2

# Create a VideoWriter object
video_writer = cv2.VideoWriter(filename, fourcc, fps, frame_size)

# Write frames in a loop
video_writer.write(frame)

# Release the writer when done
video_writer.release()
filename is the name of the output video file, like 'output.avi'.
fourcc is a code that defines the video codec, created by cv2.VideoWriter_fourcc(*'XVID').
Examples
This creates a video writer for an AVI file with 20 frames per second and frame size 640x480.
Computer Vision
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_writer = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
This adds a single frame (an image) to the video file.
Computer Vision
video_writer.write(frame)
This closes the video file properly so it can be played later.
Computer Vision
video_writer.release()
Sample Model
This program creates a 3-second video (30 frames at 10 fps) where the screen color changes from black to white gradually.
Computer Vision
import cv2
import numpy as np

# Create a VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_writer = cv2.VideoWriter('test_video.avi', fourcc, 10.0, (320, 240))

# Create 30 frames of solid colors changing from black to white
for i in range(30):
    gray_value = int(i * 255 / 29)
    frame = np.full((240, 320, 3), gray_value, dtype=np.uint8)
    video_writer.write(frame)

video_writer.release()
print('Video writing complete')
OutputSuccess
Important Notes
Make sure the frame size matches the size you specify when creating the VideoWriter.
The frame must be a color image (3 channels) or grayscale (1 channel) matching the VideoWriter settings.
Always call release() to save and close the video file properly.
Summary
Video writing saves a series of images as a video file.
Use cv2.VideoWriter with filename, codec, fps, and frame size.
Write frames with write() and close with release().