Skip to content

Instantly share code, notes, and snippets.

@yashkant
Last active February 2, 2022 06:43
Show Gist options
  • Save yashkant/d9602dfcba4f187cc3c3b26bd237d515 to your computer and use it in GitHub Desktop.
Save yashkant/d9602dfcba4f187cc3c3b26bd237d515 to your computer and use it in GitHub Desktop.
Join videos quickly row-wise or column-wise using Python
import cv2
import argparse
import glob
from torchvision.io import write_video
import numpy as np
import os
"""
A quick piece of code I put together to join some video samples I had for creating visualizations.
Limitations:
Cannot handle different aspect ratio videos (fix should be easy -- you can just rescale to fixed aspect ratio)
Args:
dir: path to directory with videos
row_vids: maximum no. of videos in a single row
Output:
A merged video made of n x row_vids grid of passed video snippets.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str, default='')
parser.add_argument('--row_vids', type=int, default=10)
def merge(vids_frames, type="horizontal"):
svf = []
for fi in range(len(vids_frames[0])):
sf = []
for vi in range(len(vids_frames)):
if fi < len(vids_frames[vi]):
sf.append(vids_frames[vi][fi])
else:
# handle when videos are different lengths
sf.append(vids_frames[vi][-1])
if type == "horizontal":
# stack horizontally
sf = np.concatenate(sf, axis=1)
else:
# stack vertically
sf = np.concatenate(sf, axis=0)
svf.append(sf)
return svf
args = parser.parse_args()
vids = glob.glob(args.dir + "/**", recursive=True)
vids = [v for v in vids if v.endswith(".mp4")]
vids_frames = []
for v in vids:
vf = []
vc = cv2.VideoCapture(v)
while vc.isOpened():
success, frame = vc.read()
if not success:
break
else:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
vf.append(frame)
vids_frames.append(vf)
# concatenate horizontally
n_rows = int(np.ceil( len(vids_frames) / args.row_vids))
vids_rows = [merge(vids_frames[i*args.row_vids:(i+1)*args.row_vids]) for i in range(n_rows)]
# stack vertically
svf = merge(vids_rows, type="vertical")
write_video(os.path.join(args.dir, 'combined.mp4'), svf, fps=10)
print(f'Written combined video to: {args.dir}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment