run2_ffmpeg_robust_extraction
Robust FFmpeg video frame extraction with error handling, alternative methods, and comprehensive frame selection strategies.
- License 许可
- MIT
- 最近更新
- 2026-10-02
- Stars
- ★ 93
- Forks
- 8
01 前言 Front Matter
- name
- run2_ffmpeg_robust_extraction
- description
- Robust FFmpeg video frame extraction with error handling, alternative methods, and comprehensive frame selection strategies.
03 SKILL.md 正文
Robust FFmpeg Frame Extraction
Overview
Extract frames from video files using FFmpeg with multiple extraction strategies, comprehensive error handling, and verification.
Installation & Verification
ffmpeg -version
Frame Extraction Strategies
Strategy 1: Key Frame Only (I-Frames) - Best for Edits
Extracts only I-frames (key frames that contain complete frame data):
ffmpeg -i input.mp4 -vf "select='eq(pict_type,I)'" -vsync 0 output_%03d.png
- Best for: Videos with clear scene changes
- Pros: Minimal output files, lowest disk usage
- Cons: May miss fast-moving objects between keyframes
Strategy 2: Fixed Frame Rate - Best for Smooth Motion
Extract frames at a fixed rate (e.g., 1 FPS, 5 FPS):
ffmpeg -i input.mp4 -vf fps=1 output_%03d.png
- Best for: Consistent time-based sampling
- Pros: Regular time intervals, predictable output count
- Cons: May be too many frames for long videos
Strategy 3: Every Nth Frame
Extract every Nth frame from the video:
ffmpeg -i input.mp4 -vf "select='isnan(prev_selected_t)+gte(t\-prev_selected_t,2)'" -vsync 0 output_%03d.png
- Best for: Uniform frame sampling
- Pros: Captures motion details
- Cons: Requires calculation for desired interval
Python Wrapper with Error Handling
import subprocess
import os
import glob
def extract_frames(input_video, output_pattern, method='keyframe'):
"""
Extract frames from video with error handling
Args:
input_video: Path to input video file
output_pattern: Output path pattern (e.g., '/root/frames_%03d.png')
method: 'keyframe' (I-frames only) or 'fps1' (1 frame per second)
Returns:
List of extracted frame paths, or None on error
"""
# Validate input
if not os.path.exists(input_video):
print(f"Error: Video file not found: {input_video}")
return None
# Choose FFmpeg filter based on method
if method == 'keyframe':
vf = "select='eq(pict_type,I)'"
vsync = "-vsync 0"
elif method == 'fps1':
vf = "fps=1"
vsync = ""
else:
print(f"Error: Unknown method: {method}")
return None
# Build FFmpeg command
cmd = f'ffmpeg -i "{input_video}" -vf "{vf}" {vsync} "{output_pattern}" 2>&1'
# Run extraction
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode != 0:
print(f"FFmpeg error: {result.stderr}")
return None
# Verify output files exist
output_dir = os.path.dirname(output_pattern)
output_prefix = os.path.basename(output_pattern).replace('%03d', '')
frames = sorted(glob.glob(os.path.join(output_dir, output_prefix.replace('.png', '')+'*.png')))
if not frames:
print("Error: No frames were extracted")
return None
print(f"Successfully extracted {len(frames)} frames")
return frames
# Usage
frames = extract_frames('/root/super-mario.mp4', '/root/keyframes_%03d.png', method='keyframe')
Video Information Query
Get video details before extraction:
ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate,duration -of default=noprint_wrappers=1 input.mp4
Best Practices
- Always validate input file before running FFmpeg
- Check available disk space - frames require significant storage
- Verify output files after extraction completes
- Use absolute paths to avoid working directory issues
- Quote file paths with spaces properly
04 同仓库更多 Skills
object_counter
Count occurrences of an object in the image using computer vision algorithm.
travel-planning-workflow
Invoke this skill when performing travel planning. It defines a structured workflow for generating itineraries. Following this workflow is essential to ensure the final plan satisfies user requirements.
bundled-dataset-search-tool
invoke this skill when you need to perform database search for travel planning. This skill provides some useful pre-packaged tools to look up accommodations, attractions, cities, driving distance, flights, and restaurants from the bundled dataset.
glm-output
Output-processing guidance for GLM tasks. Especially useful after glm-basics and glm-calibration when you need verifier-matching metrics from output.nc and a final /root/metrics.json.
glm-calibration
Calibration guidance for GLM tasks. Often most effective after glm-basics has clarified the setup; glm-output is the companion skill for exact final metric computation.
glm-basics
A good starting point for GLM calibration tasks. Use to inspect glm3.nml, confirm how GLM runs, and identify the relevant files before moving on to calibration and output evaluation.