Reputation: 33
I see questions and answers on image stitching using Open CV. Is it possible to stitch video using Open CV. Specifically using Python? I have Pycharm installed with Open CV and am able to get it to play one recorded file. But would be great to get it to read two and stitch them together. Would be grateful if anyone can point me to any tutorials that I haven't been able to find yet. Thanks
Upvotes: 0
Views: 4019
Reputation: 142631
You can use OpenCV
with for/while
loop to read frame by frame from two videos, stitch frames in new frame (using numpy
- ie. hstack()
) and save it in new file (also frame by frame)
Later I create example.
But it may be simpler to use specialized modules like MoviePy, ffmpeg-python or Manim.
Probably all of them use program ffmpeg which has many functions and filters.
Example with MoviePy
- it creates array with with two movies in one row but it can create array with many rows and columns.
from moviepy.editor import *
clip1 = VideoFileClip('input1.mp4')
clip2 = VideoFileClip('input2.mp4')
final_clip = clips_array([[clip1,clip2]]) # two videos in one row
final_clip.write_videofile('output.mp4')
And two videos in one column
final_clip = clips_array([[clip1], [clip2]]) # two videos in one column
And array 2x2 videos
final_clip = clips_array([[clip1, clip2], [clip3,clip4]])
EDIT:
Code with CV
.
It is longer and more complex but it displays video.
import cv2
import numpy as np
clip1 = cv2.VideoCapture('input1.mp4')
clip2 = cv2.VideoCapture('input2.mp4')
width = clip1.get(cv2.CAP_PROP_FRAME_WIDTH)
height = clip1.get(cv2.CAP_PROP_FRAME_HEIGHT)
fps = clip1.get(cv2.CAP_PROP_FPS)
print('fps:', fps)
video_format = cv2.VideoWriter_fourcc(*'MP42') # .avi
final_clip = cv2.VideoWriter('output.avi', video_format, fps, (int(width), int(height)))
delay = int(1000/fps)
print('delay:', delay)
while True:
ret1, frame1 = clip1.read()
ret2, frame2 = clip1.read()
if not ret1 or not ret2:
break
final_frame = np.vstack([frame1, frame2]) # two videos in one row
final_clip.write(final_frame)
cv2.imshow('Video', final_frame)
key = cv2.waitKey(delay) & 0xFF
if key == 27:
break
cv2.destroyWindow('Video')
clip1.release()
clip2.release()
Upvotes: 3