Skip to content

Instantly share code, notes, and snippets.

@hrishikeshrt
Created August 18, 2021 06:41
Show Gist options
  • Save hrishikeshrt/65673ff5c5aaad96bfa8b9186a18fe84 to your computer and use it in GitHub Desktop.
Save hrishikeshrt/65673ff5c5aaad96bfa8b9186a18fe84 to your computer and use it in GitHub Desktop.
Crop Video using ffmpeg
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Crop Video in multiple places using ffmpeg
* Input file: a text file containing several lines.
Each line should contain `start_time` and `end_time` of the interval (hh:mm:ss.ms)
e.g.
00:00:05.0 00:00:27.18
00:02:07.18 00:03:14.1
00:03:29.93 00:08:24.89
* Video file: input video file
* Output file: name for the output file
The output of the script is `ffmpeg` command string, which can be copied and executed.
Alternatively the output can be piped directly to bash,
`python crop_video.py times_demo.txt demo_raw.mp4 demo.mp4 | bash`
@author: Hrishikesh Terdalkar
"""
import sys
import datetime
input_file = sys.argv[1]
video_file = sys.argv[2]
output_file = sys.argv[3]
with open(input_file) as f:
times = [
line.split('#')[0].split()
for line in f.read().split('\n')
if line.split('#')[0].strip()
]
seconds = []
for start_time, end_time in times:
sh, sm, ss = start_time.split(':')
eh, em, es = end_time.split(':')
seconds.append([
datetime.timedelta(hours=int(sh), minutes=int(sm), seconds=float(ss)).total_seconds(),
datetime.timedelta(hours=int(eh), minutes=int(em), seconds=float(es)).total_seconds()
])
time_str = '+'.join([f'between(t,{s:.1f},{e:.1f})' for s, e in seconds])
command = (f'''ffmpeg -i {video_file} '''
f''' -vf "select='{time_str}', setpts=N/FRAME_RATE/TB"'''
f''' -af "aselect='{time_str}', asetpts=N/SR/TB"'''
f' {output_file}')
print(command)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment