-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextract_frames.py
62 lines (51 loc) · 1.98 KB
/
extract_frames.py
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
#!/usr/bin/env python
import os
import os.path
import argparse
from pprint import pp
import ffmpeg
parser = argparse.ArgumentParser(description='Extract frames')
parser.add_argument('files', type=str, nargs="*", help='Files to process')
parser.add_argument('--out', '-o', type=str, default=".", help='Output directory')
parser.add_argument('--extract-every-secs', '-s', type=float, default=1.0, help='Extract a frame every N seconds')
parser.add_argument('--frame-count', '-c', type=int, default=0, help='Number of frames to extract')
args = parser.parse_args()
OUTPATH = os.path.join(args.out, "extracted")
if not args.files:
parser.print_help()
exit(1)
for file in args.files:
try:
data = ffmpeg.probe(file)
except ffmpeg.Error as e:
print(f"!!! FAILED to probe: {file}")
print('stdout:', e.stdout.decode('utf8'))
print('stderr:', e.stderr.decode('utf8'))
continue
format = data["format"]
duration = float(format["duration"])
if args.frame_count > 0:
frames = args.frame_count
fps = frames / duration
else:
frames = int(duration / args.extract_every_secs)
fps = eval(data["streams"][0]["r_frame_rate"])
fps = 1 / args.extract_every_secs
basename = os.path.splitext(os.path.basename(file))[0]
outpath = os.path.join(OUTPATH, basename)
os.makedirs(outpath, exist_ok=True)
print(f"{file}:")
print(f" -> {outpath}")
print(f"- {duration} secs, {fps} fps, {frames} frames to extract")
try:
input = ffmpeg.input(file)
input.filter('fps', fps=fps) \
.output(os.path.join(outpath, f"{basename}_%d.png"),
#video_bitrate='5000k',
#s='64x64',
sws_flags='bilinear',
start_number=0) \
.run(capture_stdout=True, capture_stderr=True)
except ffmpeg.Error as e:
print('stdout:', e.stdout.decode('utf8'))
print('stderr:', e.stderr.decode('utf8'))