专栏名称: AirPython
分享 Python 自动化及爬虫、数据分析实战干货,欢迎关注。
目录
相关文章推荐
保险一哥  ·  一大批保险机构接上DeepSeek,你们家行 ... ·  昨天  
木木说卡  ·  速度!抓紧提额,冲飞猪大招 ·  2 天前  
每日豆瓣  ·  偷偷养胡子被妈妈发现了 ·  3 天前  
51好读  ›  专栏  ›  AirPython

短视频二次创作,Python 让效率飞起来!

AirPython  · 公众号  ·  · 2024-05-23 12:03

正文

大家好,我是安果!

视频二次创作一般操作包含分块变速、画面镜像、画面基础调整(包含亮度、饱和度、对比度等)、添加模版层

这些操作基本上都是重复性的工作,如果在爬虫结束后,将合适的片子放入队列中批量进行预处理,这样就减少 PR 或 FCPX 的工作量,大大提升剪辑效率

本篇文章聊聊具体实现方案

1、 获取当前目录下所有视频

要实现批量处理,我们需要先获取某个目录(待处理目录)下所有的视频文件

def start():    # 当前目录    folder_path = os.getcwd()
# 设置视频文件的常见扩展名 video_extensions = ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv']
video_files = []
for filename in os.listdir(folder_path): if any(filename.endswith(f".{ext}") for ext in video_extensions): video_files.append(os.path.join(folder_path, filename))

2、 视频处理

首先安装依赖包 moviepy

# 安装依赖包pip3 install moviepy

然后获取视频的长度,根据要分割的数量计算分割点

# 读取视频文件video = VideoFileClip(video_path)
# 获取视频的总时长total_duration = video.durationprint("视频名称:", output_file_name, ",时长:", total_duration)
# 分割# 计算每个分割点的时间,最后一个分割点是视频的总时长split_times = [total_duration * (i / segment_count) for i in range(segment_count)]
# 添加视频的结束时间为最后一个分割点split_times.append(total_duration)print("分割点:", split_times)

接着分割视频,对每一段进行变速处理,并调整画面亮度、画面镜像处理

# 分割视频clips = [video.subclip(split_times[i], split_times[i + 1]) for i in range(len(split_times) - 1)]
# 对每个片段进行变速处理,设置为105%速度、画面亮度调整(50%)speed_up_clips = [clip.fx(vfx.speedx, factor=speed_values[index]).fx(vfx.colorx,0.5) for index, clip in enumerate(clips)]

最后,将变速后的视频片段合并在一起写入到一个新的文件中,最后释放资源

# 将变速后的片段合并到一起final_video = CompositeVideoClip(speed_up_clips)
# 写入新的视频文件,保存变速后合并的视频(PS:导出太慢,建议使用ffmpeg命令导出)# final_video.write_videofile("speed_up_merged_video.mp4", threads=4, audio=False, logger=None, preset='ultrafast')
# 使用函数导出并合并视频temp_dir = 'temp_clips'output_path = f'{output_file_name}(new).mp4'
export_composite_to_ffmpeg(final_video, output_file=output_path, temp_dir=temp_dir)os.rmdir(temp_dir)
# 释放资源video.close()final_video.close()

需要注意的是, 利用 videopy 中 write_videofile() 方法导出视频速度很慢,建议利用 ffmpeg 命令导出处理后的视频

def export_composite_to_ffmpeg(final_video, output_file='', temp_dir="temp_clips"):    # 创建临时目录    if not os.path.exists(temp_dir):        os.makedirs(temp_dir)
# 导出每个剪辑为临时文件 temp_files = [] for i, clip in enumerate(final_video.clips): temp_file = os.path.join(temp_dir, f"clip_{i}.mp4") clip.write_videofile(temp_file) temp_files.append(temp_file)
# 创建 ffmpeg concat 文件 ffmpeg_files = "files.txt" with open(ffmpeg_files, 'w') as f: for tf in temp_files: f.write(f"file '{tf}'\n")
# 使用 ffmpeg concat 协议合并视频 ffmpeg_command = f"ffmpeg -f concat -safe 0 -i {ffmpeg_files} -c copy \"{output_file}\" -y"
# 清理临时文件 for tf in temp_files: os.remove(tf) os.remove(ffmpeg_files)

3、 快捷调用

以 windows 为例,我们只需要为 Powershell 添加快捷指令即可

在 PS 中输入命令 code $profile 打开配置文件添加快捷函数

function vp{    python D:\\video_pre.py}

这样,我们在待处理视频目录下输入 PS 命令可以一键预处理下面的所有视频

如果你觉得文章还不错,请大家 点赞、分享、留言 下,因为这将是我持续输出更多优质文章的最强动力!







请到「今天看啥」查看全文