python cv两个视频按时间前后拼接
时间: 2024-09-21 19:08:26 浏览: 35
Image-stitcher.zip
在Python中,你可以使用OpenCV(cv2库)来对两个视频进行按照时间顺序的拼接。以下是一个基本步骤的示例:
```python
import cv2
import numpy as np
# 读取两个视频文件
video1 = cv2.VideoCapture('video1.mp4')
video2 = cv2.VideoCapture('video2.mp4')
# 检查视频是否成功打开
if not (video1.isOpened() and video2.isOpened()):
print("Error opening one or both videos.")
exit()
# 获取每个视频的帧数
frame_count1 = int(video1.get(cv2.CAP_PROP_FRAME_COUNT))
frame_count2 = int(video2.get(cv2.CAP_PROP_FRAME_COUNT))
# 拼接后的总帧数
total_frames = frame_count1 + frame_count2
# 创建一个新的VideoWriter对象,指定输出视频路径、编码器等信息,以及拼接后的总帧数
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 使用常见的H.264编码
out = cv2.VideoWriter('merged_video.mp4', fourcc, video1.get(cv2.CAP_PROP_FPS), (int(video1.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video1.get(cv2.CAP_PROP_FRAME_HEIGHT))))
while True:
# 从每个视频读取一帧
ret1, frame1 = video1.read()
ret2, frame2 = video2.read()
# 如果其中一个视频结束,将另一个视频的剩余部分复制过去
if not ret1:
while ret2:
out.write(frame2)
ret2, frame2 = video2.read()
elif not ret2:
while ret1:
out.write(frame1)
ret1, frame1 = video1.read()
else:
# 如果两个都有帧,直接合并并写入输出视频
out.write(np.hstack((frame1, frame2)))
# 当读取到最后一个帧时停止
if ret1 == False and ret2 == False:
break
# 释放资源
video1.release()
video2.release()
out.release()
print("视频拼接完成.")
阅读全文