如何用Python将视频按比例转为9:16并避免像素崩坏?
解决方案:将视频转为9:16比例并保留原画质(添加黑边)
一、修正MoviePy代码(推荐)
你之前的错误是直接强制将视频拉伸到1080x1920,破坏了原视频的宽高比,导致画面变形、画质崩坏。正确做法是先按原比例缩放视频,再用黑边填充到目标9:16尺寸。
代码示例:
from moviepy.editor import VideoFileClip, ColorClip, CompositeVideoClip # 加载原视频 clip = VideoFileClip("test.mp4") target_width, target_height = 1080, 1920 # 计算原视频宽高比,获取最优缩放比例(保证画面完整不拉伸) scale_factor = min(target_width / clip.size[0], target_height / clip.size[1]) scaled_width = int(clip.size[0] * scale_factor) scaled_height = int(clip.size[1] * scale_factor) # 高质量缩放视频 scaled_clip = clip.resize(newsize=(scaled_width, scaled_height)) # 创建黑色背景画布 bg_clip = ColorClip(size=(target_width, target_height), color=(0,0,0), duration=clip.duration) # 将缩放后的视频居中叠加在背景上 final_clip = CompositeVideoClip([bg_clip, scaled_clip.set_position("center")]) # 指定编码和码率保存,避免画质损失 final_clip.write_videofile("aa.mp4", codec="libx264", bitrate="5000k")
二、使用OpenCV实现
通过逐帧处理视频,添加黑边后重新编码保存,适合需要更底层控制的场景:
import cv2 import numpy as np # 打开原视频文件 cap = cv2.VideoCapture("test.mp4") fps = cap.get(cv2.CAP_PROP_FPS) target_width, target_height = 1080, 1920 # 初始化视频写入器,指定编码格式 fourcc = cv2.VideoWriter_fourcc(*'avc1') # H.264编码,兼容性更好 out = cv2.VideoWriter("aa_opencv.mp4", fourcc, fps, (target_width, target_height)) while cap.isOpened(): ret, frame = cap.read() if not ret: break # 获取原帧尺寸,计算缩放比例 h, w = frame.shape[:2] scale_factor = min(target_width / w, target_height / h) new_w, new_h = int(w * scale_factor), int(h * scale_factor) # 使用高质量插值算法缩放帧 scaled_frame = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_LANCZOS4) # 创建黑色背景,将缩放后的帧居中放置 bg = np.zeros((target_height, target_width, 3), dtype=np.uint8) x_offset = (target_width - new_w) // 2 y_offset = (target_height - new_h) // 2 bg[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = scaled_frame # 写入处理后的帧 out.write(bg) # 释放资源 cap.release() out.release() cv2.destroyAllWindows()
关键注意事项
- 禁止直接强制修改视频尺寸,必须保留原宽高比,通过黑边填充到目标比例
- 保存视频时指定
libx264(MoviePy)或avc1(OpenCV)编码,配合合适码率避免画质损失 - 缩放时使用高质量插值算法,减少像素崩坏问题
内容的提问来源于stack exchange,提问作者ggn0
相关产品推荐
相关产品推荐

