Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

In this notebook, you’ll:

  1. Load a video file and inspect basic properties (frame count, FPS, resolution).

  2. Iterate through a few frames and display them.

  3. Fun task: Capture video from your webcam and record to a file.

Requirements: opencv-python and matplotlib (install with pip install opencv-python matplotlib if needed).

# Imports
import cv2
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path

1) Load a video and inspect properties

video_path = Path("sample_video.mp4")  # change to your file
cap = cv2.VideoCapture(str(video_path))

if not cap.isOpened():
    print("Could not open", video_path, "- please set the correct path to a local video file.")
else:
    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    width  = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    print("Frames:", frame_count, "FPS:", fps, "Resolution:", (width, height))
    cap.release()

2) Read and show a few frames

video_path = Path("sample_video.mp4")  # change to your file
cap = cv2.VideoCapture(str(video_path))

frames_to_show = 5
shown = 0

if cap.isOpened():
    while shown < frames_to_show:
        ok, frame = cap.read()
        if not ok:
            break
        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        plt.figure()
        plt.imshow(rgb)
        plt.title(f"Frame {shown+1}")
        plt.axis("off")
        shown += 1
    cap.release()
else:
    print("Open a valid video to preview frames.")

3) Task — Extract every Nth frame and save as images

# TODO: Set N and output folder, then run.
N = 30  # save every 30th frame
out_dir = Path("frames_out"); out_dir.mkdir(exist_ok=True)

video_path = Path("sample_video.mp4")  # change to your file
cap = cv2.VideoCapture(str(video_path))

if cap.isOpened():
    idx = 0
    saved = 0
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        if idx % N == 0:
            out_path = out_dir / f"frame_{idx:06d}.png"
            cv2.imwrite(str(out_path), frame)
            saved += 1
        idx += 1
    cap.release()
    print(f"Saved {saved} frames to", out_dir)
else:
    print("Open a valid video to extract frames.")

4) Fun Task — Capture webcam and record to a file

# Requires a local machine with a webcam.
# It may not work in hosted environments.

out_path = Path("webcam_capture.mp4")
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
fps = 20.0
size = (640, 480)

cap = cv2.VideoCapture(0)  # device 0
writer = cv2.VideoWriter(str(out_path), fourcc, fps, size)

if not cap.isOpened():
    print("Webcam not available.")
else:
    print("Press 'q' in the video window to stop recording...")
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        frame = cv2.resize(frame, size)
        writer.write(frame)
        cv2.imshow("Recording... (press q to quit)", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    writer.release()
    cv2.destroyAllWindows()
    print("Saved to", out_path)