目录
视频较长,分辨率较大,这个效果很好,不耗用内存 ffmpeg
imageio,适合视频较短
视频较长,分辨率较大,这个效果很好,不耗用内存 ffmpeg
import subprocess
import glob
import os
from natsort import natsorted
base_dir = r'C:\Users\Administrator\Videos\shuiyin\result'
output_file = r'output_shuiyin.mp4'
video_paths = glob.glob(base_dir + '/*.mp4')
video_paths = natsorted(video_paths)
with open('file_list.txt', 'w') as f:for file in video_paths:f.write(f"file '{file}'\n")
ffmpeg_command = ['ffmpeg','-f', 'concat', # 指定拼接模式'-safe', '0', # 允许绝对路径'-i', 'file_list.txt', # 输入的文件列表'-c:v', 'libx264', # 使用 libx264 编码器'-c:a', 'aac', # 使用 aac 编码音频'-strict', 'experimental',# 使用实验性编码output_file # 输出文件路径
]
subprocess.run(ffmpeg_command, check=True)print(f"视频拼接完成,输出文件:{output_file}")
imageio,适合视频较短
import glob
from natsort import natsorted
from moviepy.editor import VideoFileClip, concatenate_videoclips
import glob
import os.pathfrom natsort import natsorted
import cv2
import imageioif __name__ == '__main__':#内存base_dir =r"C:\Users\Administrator\Videos\shuiyin\0127"base_dir =r'C:\Users\Administrator\Videos\shuiyin\result'output_path = "pinjie_shuiyin.mp4"video_paths =glob.glob(base_dir +'/*.mp4')video_paths=natsorted(video_paths)imgs=[]res = []for file in video_paths:cap_a = cv2.VideoCapture(file) # 打开视频Bfps = cap_a.get(cv2.CAP_PROP_FPS)frame_count = 0print(file)while True:ret, frame_a = cap_a.read()if not ret:break # 如果没有读取到帧,则跳出循环res.append(cv2.cvtColor(frame_a, cv2.COLOR_BGR2RGB))frame_count += 1 # 释放视频资源cap_a.release()imageio.mimsave(output_path, res, "mp4", fps=fps, macro_block_size=None)