如何修改MoviePy脚本使其调用RTX 3090 GPU而非CPU渲染
让MoviePy脚本利用RTX 3090 GPU加速渲染
要让你的视频分割脚本在渲染阶段使用RTX 3090的GPU加速,核心是配置MoviePy调用FFmpeg时启用NVIDIA的NVENC硬件编码器,具体步骤如下:
1. 确认FFmpeg支持NVENC
先在终端/命令行执行以下命令,检查FFmpeg是否带有NVIDIA硬件加速编码器:
ffmpeg -encoders | grep nvenc
如果输出包含h264_nvenc、hevc_nvenc这类条目,说明你的FFmpeg支持GPU加速。如果没有,需要安装支持NVENC的FFmpeg版本:
- 用Conda安装:
conda install ffmpeg -c conda-forge(推荐,自带NVENC支持) - 或者从NVIDIA官网下载预编译的FFmpeg包
2. 修改脚本的渲染参数
修改原脚本中output.write_videofile()这一行,添加GPU加速相关的编码器和参数:
修改后的完整脚本
import math import moviepy.editor as mp import subprocess import sys # Define the input video file path and desired output duration input_file = "install_second_part_2x.mp4" output_duration = 158 # in seconds # Load the input video file into a moviepy VideoFileClip object video = mp.VideoFileClip(input_file) # Calculate the number of 5-second chunks in the video chunk_duration = 5 num_chunks = math.ceil(video.duration / chunk_duration) # Create a list to hold the selected chunks selected_chunks = [] # Calculate the number of chunks to select output_num_chunks = math.ceil(output_duration / chunk_duration) # Calculate the stride between adjacent chunks to select stride = num_chunks // output_num_chunks # Loop through the chunks and select every stride-th chunk for i in range(num_chunks): if i % stride == 0: chunk = video.subclip(i*chunk_duration, (i+1)*chunk_duration) selected_chunks.append(chunk) progress = i / num_chunks * 100 sys.stdout.write(f"\rProcessing: {progress:.2f}%") sys.stdout.flush() # Keep adding chunks until the output duration is reached output = selected_chunks[0] for chunk in selected_chunks[1:]: if output.duration < output_duration: output = mp.concatenate_videoclips([output, chunk]) else: break # Write the output video to a file with GPU acceleration output_file = "install_part_cut.mp4" # 使用H.264 NVENC编码器,指定预设和GPU编号 output.write_videofile( output_file, codec='h264_nvenc', # 若要H.265编码可改为'hevc_nvenc' preset='fast', # 预设模式:fast/medium/slow,速度越快质量稍降 ffmpeg_params=['-gpu', '0'], # 指定使用第0块GPU(RTX3090) threads=4 # 辅助线程数,可根据CPU情况调整 )
关键修改说明
codec='h264_nvenc':指定使用NVIDIA的H.264硬件编码器,替代默认的CPU编码器preset='fast':控制编码速度和质量的平衡,fast速度快,slow质量更高但耗时久ffmpeg_params=['-gpu', '0']:明确指定使用第0块GPU(如果有多块GPU可调整编号)threads=4:设置辅助的CPU线程数,避免CPU成为瓶颈
运行修改后的脚本,就能看到RTX 3090的GPU使用率上升,渲染速度会大幅提升。
内容的提问来源于stack exchange,提问作者Furkan Gözükara
相关产品推荐
相关产品推荐

