注意:视频拼接之前需要确保两个视频的帧率相同,如果视频帧率不同,使用下面的命令来调整一个视频的帧率为目标帧率
ffmpeg -i 原视频.mp4 -r 目标帧率 output.mp4
视频拼接代码,在拼接的时候会将两个原始视频的分辨率统一缩放为target_width和target_height,输出的视频会存放在merged_video.mp4中
import cv2
import numpy as np
# 打开两个视频文件
cap1 = cv2.VideoCapture("data/1.mp4")
cap2 = cv2.VideoCapture("data/2.mp4")
# 获取视频的帧率
fps = cap1.get(cv2.CAP_PROP_FPS)
fps2 = cap2.get(cv2.CAP_PROP_FPS)
# 确保两个视频的帧率相同
assert fps == fps2
# 目标分辨率
target_width = 960
target_height = 544
# 创建输出视频文件
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter("merged_video.mp4", fourcc, fps, (target_width, target_height * 2))
while cap1.isOpened() and cap2.isOpened():
ret1, frame1 = cap1.read()
ret2, frame2 = cap2.read()
if not ret1 or not ret2:
break
# 缩放视频帧到目标分辨率
resized_frame1 = cv2.resize(frame1, (target_width, target_height))
resized_frame2 = cv2.resize(frame2, (target_width, target_height))
# 上下拼接帧
merged_frame = np.vstack((resized_frame1, resized_frame2))
# 写入输出视频
out.write(merged_frame)
# 释放资源
cap1.release()
cap2.release()
out.release()
评论区