主要是由于视频的色彩空间引起的
代码语言:javascript复制import cv2
from moviepy.editor import VideoFileClip, AudioFileClip
import time
# 输入视频文件路径
input_video_path = '/Users/a3530/Downloads/b62398c3af39755f6e7e5da6bec2bdce480p.mp4'
def get_new_video(input_video_path):
input_video_name = input_video_path.split("/")[-1]
input_audio_path = input_video_name.replace("mp4","mp3")
# 输出视频文件路径
output_video_path = f'tmp_{input_video_name}'
res_video_path = f'new_{input_video_name}'
# 打开输入视频文件
video_clip = VideoFileClip(input_video_path)
# 提取视频的音频部分
audio_clip = video_clip.audio
# 保存音频文件
audio_clip.write_audiofile(input_audio_path, codec='mp3')
print("提取音频结束")
# 打开输入视频文件
cap = cv2.VideoCapture(input_video_path)
# 获取输入视频的参数
frame_width = int(cap.get(3)) # 获取帧宽度
frame_height = int(cap.get(4)) # 获取帧高度
fps = int(cap.get(5)) # 获取帧率
# 设置输出视频编码器为H.264
fourcc = cv2.VideoWriter_fourcc(*'H264')
# 创建输出视频文件
out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))
# 逐帧读取、转换、写入
while True:
ret, frame = cap.read() # 读取一帧
if not ret:
break # 如果没有更多帧可读,退出循环
# 在这里进行颜色空间转换,确保将颜色描述转换为HD (1-1-1)的RGB空间
# 这里的示例是复制帧,你可以根据需要进行颜色空间转换
# 写入帧到输出视频文件
out.write(frame)
# 释放视频对象
cap.release()
out.release()
print("修改视频色彩空间结束")
# 打开输入视频文件
video_clip = VideoFileClip(output_video_path)
# 打开输入音频文件
audio_clip = AudioFileClip(input_audio_path)
video_with_audio_clip = video_clip.set_audio(audio_clip)
video_with_audio_clip.write_videofile(res_video_path, codec='libx264')
print("视频添加音频完成")
return res_video_path
if __name__ == '__main__':
print(get_new_video(input_video_path))