Python视频宽高比处理代码:横向正常纵向失效问题求助
纵向视频宽高比处理失效问题
我用Python编写的视频宽高比处理代码在横向视频上运行正常,但处理纵向视频时完全失效。先后尝试了两种基于FFmpeg的实现方案,问题仍未解决,具体代码如下:
def apply_aspect_ratio(video_path: str, aspect_ratio: str, output_path: str) -> None: target_width, target_height = map(int, aspect_ratio.split(':')) width, height = get_video_size(video_path) scale_width = width / target_width scale_height = height / target_height if scale_width > scale_height: # 横向填充 pad = int(((width / target_width * target_height) - height) / 2) filter_string = f"pad={width}:{width//target_width*target_height}:(ow-iw)/2:{pad}" # filter_string = f"scale={width}:{new_height},pad={width}:{new_height}:{pad_top}:{pad_bottom}" else: # 纵向填充 pad = int(((height / target_height * target_width) - width) / 2) filter_string = f"pad={height//target_height*target_width}:{height}:(ow-iw)/2:{pad}" cmd = [ 'ffmpeg', '-i', video_path, '-vf', filter_string, '-c:v', 'libx264', '-preset', 'fast', output_path ] subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print(f"Applied aspect ratio = {aspect_ratio} to {video_path}")
我尝试了这种方案但仍然无效
import subprocess def apply_aspect_ratio(video_path: str, aspect_ratio: str, output_path: str) -> None: # 拆分目标宽高比 target_width, target_height = map(int, aspect_ratio.split(':')) # 获取视频原始尺寸 width, height = get_video_size(video_path) # 计算缩放比例 scale_width = width / target_width scale_height = height / target_height # 计算填充参数 if scale_width > scale_height: # 横向填充 new_height = int(width / target_width * target_height) pad_top = (new_height - height) // 2 pad_bottom = new_height - height - pad_top filter_string = f"scale={width}:{new_height},pad={width}:{new_height}:{pad_top}:{pad_bottom}" else: # 纵向填充 new_width = int(height / target_height * target_width) pad_left = (new_width - width) // 2 pad_right = new_width - width - pad_left filter_string = f"scale={new_width}:{height},pad={new_width}:{height}:{pad_left}:{pad_right}" # 构建FFmpeg命令 cmd = [ 'ffmpeg', '-i', video_path, '-vf', filter_string, '-c:v', 'libx264', '-preset', 'fast', output_path ] subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print(f"Applied aspect ratio = {aspect_ratio} to {video_path}") def get_video_size(video_path: str): cmd = [ 'ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'csv=s=x:p=0', video_path ] result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) width, height = map(int, result.stdout.strip().split('x')) return width, height
内容的提问来源于stack exchange,提问作者Junbutaw Tawbutaw
相关产品推荐
相关产品推荐

