软硬件环境
- anaconda with python 3.8
- opencv 4.5
前言
为达到将2个视频拼接成一个的目的,本文使用了最简单的逐帧拼接的方法,要求输入视频的尺寸一致。
代码实现
import cv2
import numpy as np
# 分别读取2个视频
videoLeft = cv2.VideoCapture('left.mp4')
videoRight = cv2.VideoCapture('right.mp4')
# 获取fps、宽和高
fps = videoLeft.get(cv2.CAP_PROP_FPS)
width = (int(videoLeft.get(cv2.CAP_PROP_FRAME_WIDTH)))
height = (int(videoLeft.get(cv2.CAP_PROP_FRAME_HEIGHT)))
videoWriter = cv2.VideoWriter('output1.mp4', cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), fps, (width, height))
# 分别从2个视频中读取第一帧的数据
successLeft,frameLeft = videoLeft.read()
successRight, frameRight = videoRight.read()
while successLeft and successRight:
# resize操作,都是高度不变,宽度缩小一半,这样拼接后的就是原来的宽和高了
frameLeft = cv2.resize(frameLeft, (int(width / 2), int(height)), interpolation=cv2.INTER_CUBIC)
frameRight = cv2.resize(frameRight, (int(width / 2), int(height)), interpolation=cv2.INTER_CUBIC)
# numpy操作,在水平方向堆叠数组ndarray,也就是图片堆叠,垂直方向上的操作是vstack
frame = np.hstack((frameLeft, frameRight))
# 保存处理后的视频帧
videoWriter.write(frame)
# 读取下一帧数据,循环处理
successLeft,frameLeft = videoLeft.read()
successRight, frameRight = videoRight.read()
# 释放资源
videoWriter.release()
videoLeft.release()
videoRight.release()
下面两张是原始视频中的图片
执行上述代码,合成后的效果如下