opencv | motion detection | python write images to ffmpeg stream | Search

The code imports OpenCV and glob libraries, sets output video properties, and defines a write_video function that creates an output video from a list of images. The function gets the list of images, defines a VideoWriter object, writes each image to the video, and releases the object after cleanup.

Run example

npm run import -- "python write video"

python write video

import cv2
import glob

# Set output video properties
fps = 30
output_file = "output.mp4"

def write_video():
  # Get list of images
  image_files = sorted(glob.glob("frame_*.jpg"))  # Adjust pattern as needed

  # Read first image to get dimensions
  frame = cv2.imread(image_files[0])
  height, width, _ = frame.shape

  # Define VideoWriter object
  fourcc = cv2.VideoWriter_fourcc(*"mp4v")  # Codec
  out = cv2.VideoWriter(output_file, fourcc, fps, (width, height))

  # Write images to video
  for img_path in image_files:
      frame = cv2.imread(img_path)
      out.write(frame)

  # Cleanup
  out.release()
  cv2.destroyAllWindows()

__all__ = {
  "write_video": write_video
}

What the code could have been:

import cv2
import glob

Code Breakdown

Importing Libraries

The code starts by importing two libraries:

Setting Output Video Properties

The code sets two properties for the output video:

write_video Function

The write_video function takes care of creating the output video. Here's a step-by-step breakdown:

  1. Get list of images: It uses glob to find all files with the pattern "frame_*.jpg" and sorts the list.
  2. Read first image to get dimensions: It reads the first image in the list using cv2.imread to get the dimensions (height and width).
  3. Define VideoWriter object: It creates a VideoWriter object using cv2.VideoWriter, specifying the codec ("mp4v"), frame rate (30), and frame dimensions (height and width).
  4. Write images to video: It iterates over the list of images and writes each image to the video using out.write(frame).
  5. Cleanup: It releases the VideoWriter object and closes all OpenCV windows using cv2.destroyAllWindows.

Exporting the write_video Function

The code exports the write_video function using the __all__ attribute, making it available for import in other modules.