#------------------------------------------------------------------------------ #Ref: karobben.github.io/2021/04/10/Python/opencv-v-paste #This code adds two videos side by side. The second video is scaled to the #height of the first video. Audio is not copied. The duration of each video is #assumed to be equal. Code was tested on a video of resolution 1280x720 and #the resultant video having size 2560x720 could be opened without any error on #Ubuntu LTS 22.0, 15.4" monitor of resolution 100 DPI. #------------------------------------------------------------------------------ import cv2 #Read the input videos and specify name of the output video Vid1 = "v1.mp4" Vid2 = "v2.mp4" Out = "out.mp4" cap1 = cv2.VideoCapture(Vid1) cap2 = cv2.VideoCapture(Vid2) Window = None #or '1920x1080' or '1280x720' - check Aspect Ratio of input #Get the fps and the size of the Video one fps1 = cap1.get(cv2.CAP_PROP_FPS) h1 = cap1.get(cv2.CAP_PROP_FRAME_HEIGHT) w1 = cap1.get(cv2.CAP_PROP_FRAME_WIDTH) nfrm = cap1.get(cv2.CAP_PROP_FRAME_COUNT) fps_c2 = cap2.get(cv2.CAP_PROP_FPS) h2 = cap2.get(cv2.CAP_PROP_FRAME_HEIGHT) w2 = cap2.get(cv2.CAP_PROP_FRAME_WIDTH) def frameConnect(f1, f2, h1, w1, h2, w2): f2 = cv2.resize(f2, (int(w2), int(h1)), interpolation = cv2.INTER_AREA) BG = cv2.resize(f1, (int(w1 + w2), int(h1)),interpolation=cv2.INTER_AREA) BG[0:int(h1),0:int(w1)] = f1 BG[0:int(h1),int(w1):int(w1+w2)] = f2 return (BG) # Set argument for Video Output fps = fps1 if Window == None: size = (int(w1+w2), int(h1)) else: size = (int(Window.split("x")[0]), int(Window.split("x")[1])) fourcc = cv2.VideoWriter_fourcc('m','p','4','v') videowriter = cv2.VideoWriter(Out,fourcc,fps,size) i = 1 while (i < nfrm): #Prevent reading Null image, the LAST frame of the video ret,f1=cap1.read() ret,f2=cap2.read() img = frameConnect(f1, f2, h1, w1, h2, w2) img = cv2.resize(img, size, interpolation = cv2.INTER_AREA) videowriter.write(img) i = i + 1