Skip to content

Instantly share code, notes, and snippets.

@crearo
Created December 15, 2017 10:50
Show Gist options
  • Save crearo/2b651849506c9df87d6aab2e78c6c8a6 to your computer and use it in GitHub Desktop.
Save crearo/2b651849506c9df87d6aab2e78c6c8a6 to your computer and use it in GitHub Desktop.
Takes two input videos of the same dimensions and stores them side by side
'''
A small script to play videos of the same dimensions side by side.
I needed this while showing two videos side by side; one stabilized and one not stabilized during my
works on video stabilization.
'''
import cv2, sys
import numpy as np
if len(sys.argv) < 3:
raise ValueError('[folder] [to_crop T F] [crop %]')
folder = sys.argv[1]
to_crop = sys.argv[2].lower() == "T"
crop_factor = float(sys.argv[3]) if to_crop else 0
print ('cropping parameter set to %d' % (crop_factor*100) if to_crop else 'not cropping image')
resize_factor = 1
if(crop_factor < 0 or crop_factor >= 0.5):
raise ValueError('crop factor to be [0,5)')
vid = cv2.VideoCapture('%sraw.mp4' % (folder))
vid2 = cv2.VideoCapture('%sstabilized.mp4' %(folder))
orig_width = int(vid.get(3))
orig_height = int(vid.get(4))
x1 = int(orig_width * crop_factor) if to_crop else 0
x2 = int(orig_width * (1-crop_factor)) if to_crop else orig_width
y1 = int(orig_height * crop_factor) if to_crop else 0
y2 = int(orig_height * (1-crop_factor)) if to_crop else orig_height
print ('cropped rect :',x1,x2,y1,y2,x2-x1,y2-y1)
# because 2 frames are placed side by side, we multiply width by 2
out_frame_width = int(2 * (x2-x1) * resize_factor)
out_frame_height = int((y2-y1) * resize_factor)
print ('outsize :', out_frame_width, out_frame_height)
fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter('%sboth%s.avi'%(folder, '-crop-%.2f'%(crop_factor) if to_crop else '-full'), fourcc, 20.0, (out_frame_width,out_frame_height))
while (vid.isOpened()):
ret1, frame1 = vid.read()
ret2, frame2 = vid2.read()
if ret1 and ret2:
if to_crop:
# NOTE: its img[y: y + h, x: x + w] and *not* img[x: x + w, y: y + h]
frame1 = frame1[y1 : y2, x1 : x2]
frame2 = frame2[y1 : y2, x1 : x2]
frame1 = cv2.resize(frame1, (0,0), fx=resize_factor, fy=resize_factor)
frame2 = cv2.resize(frame2, (0,0), fx=resize_factor, fy=resize_factor)
both = np.hstack((frame1,frame2))
out.write(both)
# cv2.imshow('frame', both)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
else:
break
out.release()
vid.release()
vid2.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment