-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideo_to_frames.py
More file actions
263 lines (216 loc) · 8.3 KB
/
video_to_frames.py
File metadata and controls
263 lines (216 loc) · 8.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/usr/bin/env python3
"""
Video to Frames Extractor using FFmpeg
A command-line tool to extract frames from video files using FFmpeg.
Supports various output formats (JPG, PNG, WebP) and customizable frame rates.
Usage:
python video_to_frames.py input.mp4 -o output_dir -f 1 --format jpg
"""
import argparse
import subprocess
import sys
import os
import shutil
from pathlib import Path
def check_ffmpeg():
"""Check if FFmpeg is installed and accessible."""
if shutil.which("ffmpeg") is None:
print("Error: FFmpeg is not installed or not in PATH.")
print("Please install FFmpeg:")
print(" - macOS: brew install ffmpeg")
print(" - Ubuntu/Debian: sudo apt install ffmpeg")
print(" - Windows: Download from https://ffmpeg.org/download.html")
sys.exit(1)
def get_video_info(video_path):
"""Get video information using ffprobe."""
cmd = [
"ffprobe",
"-v", "error",
"-select_streams", "v:0",
"-show_entries", "stream=width,height,r_frame_rate,duration",
"-of", "csv=p=0",
str(video_path)
]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
parts = result.stdout.strip().split(",")
if len(parts) >= 3:
width = int(parts[0])
height = int(parts[1])
# Parse frame rate (e.g., "30/1" or "30000/1001")
fps_parts = parts[2].split("/")
fps = float(fps_parts[0]) / float(fps_parts[1]) if len(fps_parts) == 2 else float(fps_parts[0])
duration = float(parts[3]) if len(parts) > 3 and parts[3] else None
return {
"width": width,
"height": height,
"fps": fps,
"duration": duration
}
except (subprocess.CalledProcessError, ValueError, IndexError) as e:
print(f"Warning: Could not get video info: {e}")
return None
def extract_frames(
video_path,
output_dir,
fps=1,
format="jpg",
quality=90,
start_time=None,
end_time=None,
prefix="frame",
scale=None
):
"""
Extract frames from video using FFmpeg.
Args:
video_path: Path to input video file
output_dir: Directory to save extracted frames
fps: Frames per second to extract (default: 1)
format: Output format - jpg, png, or webp (default: jpg)
quality: Image quality 1-100 (default: 90)
start_time: Start time in seconds (optional)
end_time: End time in seconds (optional)
prefix: Filename prefix for output frames (default: frame)
scale: Output resolution as "width:height" (optional, e.g., "1920:1080" or "-1:720")
Returns:
Number of frames extracted
"""
video_path = Path(video_path)
output_dir = Path(output_dir)
if not video_path.exists():
raise FileNotFoundError(f"Video file not found: {video_path}")
# Create output directory
output_dir.mkdir(parents=True, exist_ok=True)
# Build FFmpeg command
cmd = ["ffmpeg", "-y"] # -y to overwrite without asking
# Input time range (before -i for faster seeking)
if start_time is not None:
cmd.extend(["-ss", str(start_time)])
# Input file
cmd.extend(["-i", str(video_path)])
# End time (after -i)
if end_time is not None:
if start_time is not None:
duration = end_time - start_time
cmd.extend(["-t", str(duration)])
else:
cmd.extend(["-t", str(end_time)])
# Video filters
filters = []
# Frame rate filter
filters.append(f"fps={fps}")
# Scale filter (optional)
if scale:
filters.append(f"scale={scale}")
if filters:
cmd.extend(["-vf", ",".join(filters)])
# Output format and quality settings
if format.lower() == "jpg" or format.lower() == "jpeg":
ext = "jpg"
cmd.extend(["-q:v", str(int((100 - quality) * 31 / 100 + 1))]) # FFmpeg uses 1-31, lower is better
elif format.lower() == "png":
ext = "png"
# PNG compression level (0-9, higher = more compression but slower)
compression = int((100 - quality) * 9 / 100)
cmd.extend(["-compression_level", str(compression)])
elif format.lower() == "webp":
ext = "webp"
cmd.extend(["-quality", str(quality)])
else:
raise ValueError(f"Unsupported format: {format}. Use jpg, png, or webp.")
# Output pattern
output_pattern = output_dir / f"{prefix}_%04d.{ext}"
cmd.append(str(output_pattern))
# Run FFmpeg
print(f"Extracting frames from: {video_path}")
print(f"Output directory: {output_dir}")
print(f"Settings: {fps} fps, {format.upper()} format, quality {quality}")
print(f"Running: {' '.join(cmd)}")
print()
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
check=True
)
except subprocess.CalledProcessError as e:
print(f"FFmpeg error: {e.stderr}")
raise
# Count extracted frames
frame_files = list(output_dir.glob(f"{prefix}_*.{ext}"))
frame_count = len(frame_files)
print(f"Successfully extracted {frame_count} frames to {output_dir}")
return frame_count
def main():
parser = argparse.ArgumentParser(
description="Extract frames from video files using FFmpeg",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Extract 1 frame per second as JPG
python video_to_frames.py video.mp4 -o frames/
# Extract at original frame rate as PNG
python video_to_frames.py video.mp4 -o frames/ -f 30 --format png
# Extract frames from 10s to 20s at 2 fps
python video_to_frames.py video.mp4 -o frames/ -f 2 --start 10 --end 20
# Extract with custom prefix and quality
python video_to_frames.py video.mp4 -o frames/ --prefix screenshot --quality 95
# Extract and resize to 720p height
python video_to_frames.py video.mp4 -o frames/ --scale -1:720
"""
)
parser.add_argument("video", help="Path to input video file")
parser.add_argument("-o", "--output", default="frames", help="Output directory (default: frames)")
parser.add_argument("-f", "--fps", type=float, default=1, help="Frames per second to extract (default: 1)")
parser.add_argument("--format", choices=["jpg", "png", "webp"], default="jpg", help="Output image format (default: jpg)")
parser.add_argument("-q", "--quality", type=int, default=90, help="Image quality 1-100 (default: 90)")
parser.add_argument("--start", type=float, help="Start time in seconds")
parser.add_argument("--end", type=float, help="End time in seconds")
parser.add_argument("--prefix", default="frame", help="Filename prefix (default: frame)")
parser.add_argument("--scale", help="Output resolution, e.g., '1920:1080' or '-1:720' (keep aspect ratio)")
parser.add_argument("--info", action="store_true", help="Show video information and exit")
args = parser.parse_args()
# Check FFmpeg installation
check_ffmpeg()
# Check if video file exists
if not os.path.exists(args.video):
print(f"Error: Video file not found: {args.video}")
sys.exit(1)
# Show video info
info = get_video_info(args.video)
if info:
print(f"Video Information:")
print(f" Resolution: {info['width']}x{info['height']}")
print(f" Frame Rate: {info['fps']:.2f} fps")
if info['duration']:
print(f" Duration: {info['duration']:.2f} seconds")
total_frames = int(info['duration'] * info['fps'])
print(f" Total Frames: ~{total_frames}")
print()
if args.info:
sys.exit(0)
# Extract frames
try:
frame_count = extract_frames(
video_path=args.video,
output_dir=args.output,
fps=args.fps,
format=args.format,
quality=args.quality,
start_time=args.start,
end_time=args.end,
prefix=args.prefix,
scale=args.scale
)
if frame_count > 0:
print(f"\nDone! {frame_count} frames saved to '{args.output}/'")
else:
print("\nWarning: No frames were extracted. Check your settings.")
sys.exit(1)
except Exception as e:
print(f"\nError: {e}")
sys.exit(1)
if __name__ == "__main__":
main()