python+opencv横向拼接视频

如果想利用python+opencv把两段视频拼接在一起,可以有两种想法:

1. 第二个视频直接接在第一个视频后边,延长帧。这种我称为“纵向拼接”;

2. 第一个视频和第二个视频每一帧平铺,这样就可以同时看两个视频了;

如果你是第1个目的点进本文的,那么不好意思,本文不满足你的要求。本文主要面向横向拼接视频,把自己写的脚本记录一下,免得下次再写~

import cv2
import numpy as np

INPUT_FILE1 = 'clip1.avi'
INPUT_FILE2 = 'clip2.avi'
OUTPUT_FILE = 'merge.avi'

reader1 = cv2.VideoCapture(INPUT_FILE1)
reader2 = cv2.VideoCapture(INPUT_FILE2)
width = int(reader1.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(reader1.get(cv2.CAP_PROP_FRAME_HEIGHT))
writer = cv2.VideoWriter(OUTPUT_FILE,
              cv2.VideoWriter_fourcc('I', '4', '2', '0'),
              30, # fps
              (width, height//2)) # resolution

print(reader1.isOpened())
print(reader2.isOpened())
have_more_frame = True
c = 0
while have_more_frame:
    have_more_frame, frame1 = reader1.read()
    _, frame2 = reader2.read()
    frame1 = cv2.resize(frame1, (width//2, height//2))
    frame2 = cv2.resize(frame2, (width//2, height//2))
    img = np.hstack((frame1, frame2))
    cv2.waitKey(1)
    writer.write(img)
    c += 1
    print(str(c) + ' is ok')


writer.release()
reader.release()
cv2.destroyAllWindows()

非常要注意的是VideoWriter中宽和高的设置,因为咱是拼接视频,所以对影响原本的宽和高。

你可能感兴趣的:(Computer,Vision,python,tools)