Reading Video Files
OpenCV's VideoCapture class handles reading from both video files and live cameras. The same API works for both.
8 min•By Priygop Team•Updated 2026
Video Reading Pipeline
Video Reading Pipeline
import cv2
import time
def process_video_file(video_path, process_fn=None, max_frames=None):
"""
Read and process a video file frame by frame.
process_fn: optional function to apply to each frame
"""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Error: Could not open '{video_path}'")
return
fps = cap.get(cv2.CAP_PROP_FPS)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(f"Processing: {video_path} ({total_frames} frames at {fps:.1f} FPS)")
frame_count = 0
start_time = time.time()
while True:
ret, frame = cap.read()
if not ret:
print("End of video reached")
break
if max_frames and frame_count >= max_frames:
print(f"Reached max_frames limit ({max_frames})")
break
# Apply processing function if provided
if process_fn:
frame = process_fn(frame)
frame_count += 1
# Log progress every 100 frames
if frame_count % 100 == 0:
elapsed = time.time() - start_time
proc_fps = frame_count / elapsed
pct = frame_count / total_frames * 100
print(f" Frame {frame_count}/{total_frames} ({pct:.1f}%) — {proc_fps:.1f} FPS")
cap.release()
elapsed = time.time() - start_time
print(f"Done: {frame_count} frames in {elapsed:.1f}s ({frame_count/elapsed:.1f} FPS)")
# Example: convert video to grayscale
def make_grayscale(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
return cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) # Convert back for saving
process_video_file("input.mp4", process_fn=make_grayscale, max_frames=300)Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment