Frame Reduction Script — Understanding the Packages¶
This notebook processes all video files in a given directory and creates new videos where every other frame is skipped, while preserving the original video duration.
Packages Used¶
1. os
Lets us interact with the file system
We use it to:
Loop through files in a directory
Build input/output file paths
Check file extensions
2. cv2 (OpenCV)
A computer vision library for reading, writing, and manipulating videos and images
We use it to:
Open each video file
Read frames one by one
Resize frames
Write output videos with modified frames
3. tqdm (optional but recommended)
Creates progress bars
Makes it easier to see the processing progress for each video
Output Format¶
For an input file like: walking.mp4
The output file will be: walking_FrameReduced.mp4
in the same directory, and the video will keep its original duration even though half the frames are removed.
How We Keep the Original Duration¶
If we skip every other frame, we effectively output half the frames.
To keep the video length the same, we also halve the FPS when writing the output video.
Example:
Input video: 120 FPS, 600 frames → 20 seconds
Output video: 60 FPS, 300 frames → still 20 seconds
This preserves video timing.
Make the Python Function¶
import os
import cv2
from tqdm import tqdm
def reduce_frames_in_directory(directory_path: str):
# Supported video extensions
VIDEO_EXTENSIONS = ('.mp4', '.mov', '.avi', '.mkv', '.flv')
# List all video files in the directory
files = [f for f in os.listdir(directory_path) if f.lower().endswith(VIDEO_EXTENSIONS)]
if not files:
print("No video files found in the directory.")
return
for file in files:
input_path = os.path.join(directory_path, file)
basename, ext = os.path.splitext(file)
output_filename = f"{basename}_FrameReduced{ext}"
output_path = os.path.join(directory_path, output_filename)
print(f"\nProcessing: {file}")
cap = cv2.VideoCapture(input_path)
if not cap.isOpened():
print(f"Could not open {file}. Skipping.")
continue
# Read input video properties
input_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))
# New FPS = half the original
output_fps = input_fps / 2
# Video writer
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter(output_path, fourcc, output_fps, (width, height))
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Loop through frames
for i in tqdm(range(frame_count), desc=f"Writing {output_filename}"):
ret, frame = cap.read()
if not ret:
break
# Skip every other frame → keep even-numbered frames only
if i % 2 == 0:
out.write(frame)
cap.release()
out.release()
print(f"Saved: {output_filename}")
RUN THE FUNCTION BELOW¶
# Example:
directory_path = "path/to/yours/videos"
reduce_frames_in_directory(directory_path)