Python-批量修改视频分辨率
1 使用Python修改视频分辨率
首先拷贝视频文件并修改后缀,然后修改图片的分辨率,实现视频批量修改和转换。
import os
import cv2
from pathlib import Path
source_path = r"D:/VideoDir"
sink_path = r"D:/VideoDir_New"
if not os.path.exists(source_path):
print('Source path not exit!')
exit()
if not os.path.exists(sink_path):
os.mkdir(sink_path)
print('Create sink path!')
videos_list = os.listdir(source_path)
for video in videos_list:
video_path = os.path.join(source_path, video)
if Path(video_path).suffix in ['.MOV', '.mov', '.mp4']:
print(f"开始处理:{video_path}!")
# 修改后缀名
dis_video_name = video
dis_video_name = dis_video_name.replace(str(dis_video_name).split('.')[-1], 'avi')
dis_path = os.path.join(sink_path, dis_video_name)
# 进行转换
cap = cv2.VideoCapture(video_path)
success, _ = cap.read()
# 重新合成的视频在原文件夹,如果需要分开,可以修改file_n
video_writer = cv2.VideoWriter(dis_path, cv2.VideoWriter_fourcc(*'XVID'), 25, (1280, 720))
while success:
success, vid1 = cap.read()
try:
vid = cv2.resize(vid1, (1280, 720), interpolation=cv2.INTER_LINEAR) # 希望的分辨率大小可以在这里改
video_writer.write(vid)
except:
break
print(f"处理完毕:{video_path}!")
2 修改视频分辨率并保留音频
from moviepy.editor import VideoFileClip, AudioFileClip
def change_video_resolution(input_video_path, output_video_path, new_width, new_height):
video_clip = VideoFileClip(input_video_path)
audio_clip = video_clip.audio
video_clip_resized = video_clip.resize((new_width, new_height))
# 将修改过分辨率的视频和原始音频合成新视频
final_clip = video_clip_resized.set_audio(audio_clip)
final_clip.write_videofile(output_video_path, codec='libx264', audio_codec='aac')
# 使用函数修改视频分辨率
input_video_path = 'input.mp4' # 输入视频文件路径
output_video_path = 'output.mp4' # 输出视频文件路径
change_video_resolution(input_video_path, output_video_path, new_width=1280, new_height=720)
3 常见的视频编码格式
3.1 等效的编码格式表示方式
cv2.VideoWriter_fourcc(*'mp4v')
cv2.VideoWriter_fourcc(*'MP4V')
cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
3.2 常见的编码格式
1. cv2.VideoWriter_fourcc('M', 'P', '4', 'V') MPEG-4编码 .mp4 可指定结果视频的大小
2. cv2.VideoWriter_fourcc('X','2','6','4') MPEG-4编码 .mp4 可指定结果视频的大 小
3. cv2.VideoWriter_fourcc('I', '4', '2', '0') 该参数是YUV编码类型,文件名后缀为.avi
广泛兼容,但会产生大文件
4. cv2.VideoWriter_fourcc('P', 'I', 'M', 'I') 该参数是MPEG-1编码类型,文件名后缀为.avi
5. cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
该参数是MPEG-4编码类型,文件名后缀为.avi,可指定结果视频的大小
6. cv2.VideoWriter_fourcc('T', 'H', 'E', 'O') 该参数是Ogg Vorbis,文件名后缀为.ogv
7. cv2.VideoWriter_fourcc('F', 'L', 'V', '1') 该参数是Flash视频,文件名后缀为.flv