赞
踩
本文将介绍 Python 中常用的视频处理库和工具,包括 cv2、requests、numpy、moviepy 等,帮助读者了解它们的功能和用法,并展示如何使用这些工具进行图像处理、视频编辑和音频处理。
个人倾向于第二种,直接访问线上资源地址进行处理,简洁高效,避免了繁琐的本地缓存和管理。不仅节省了时间,同时还节省了服务器或者计算机资源。
import os import cv2 from moviepy.editor import AudioFileClip # 图片文件夹路径 ims_folder = './images' # 图片存放路径 audio_path = './music/audio.mp3' # 音频存放路径 video_path = './synthesis/image_audio.mp4' # 合成后保存路径以及视频名称 # 获取图片文件列表并排序 ims_path_list = sorted(os.listdir(ims_folder)) # 创建 AudioFileClip 对象 audio_clip = AudioFileClip(audio_path) # 计算视频时长和帧率 desired_duration = audio_clip.duration fps = len(ims_path_list) / desired_duration frames_per_image = int(fps * (desired_duration / len(ims_path_list))) # 设置视频编码器为MP4V fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 获取第一张图片的尺寸 first_im_path = os.path.join(ims_folder, ims_path_list[0]) first_image = cv2.imread(first_im_path) im_size = (first_image.shape[1], first_image.shape[0]) # 创建视频写入对象 videoWriter = cv2.VideoWriter(video_path, fourcc, fps, im_size) # 遍历每张图片,将其写入视频文件 for im_path in ims_path_list: im_path = os.path.join(ims_folder, im_path) # 读取图片并调整大小 frame = cv2.resize(cv2.imread(im_path), im_size) # 写入每张图片对应的帧数 for _ in range(frames_per_image): videoWriter.write(frame) # 释放视频写入对象 videoWriter.release() print('合成完成')
import cv2 import requests import numpy as np from moviepy.editor import VideoFileClip, ImageSequenceClip, concatenate_videoclips from moviepy.audio.io.AudioFileClip import AudioFileClip def get_image_from_url(url): response = requests.get(url) image_data = response.content image_np = cv2.imdecode(np.frombuffer(image_data, np.uint8), cv2.IMREAD_COLOR) return image_np # 图片的URL列表 image_urls = [] # 视频输出路径 video_path = "video.mp4" # 音频URL audio_url = "" def create_video_from_images(image_urls, audio_url, video_path): # 获取音频时长 audio_clip = AudioFileClip(audio_url) audio_duration = audio_clip.duration # 计算每张图片需要出现的时间 num_images = len(image_urls) frame_duration = audio_duration / num_images # 获取第一张图片的尺寸 first_image = get_image_from_url(image_urls[0]) im_size = (first_image.shape[1], first_image.shape[0]) # 创建视频写入对象 video_clips = [] # 将每张图片添加到视频中,并设置每张图片的显示时间 for i, image_url in enumerate(image_urls): # 获取图片数据并调整大小 image_np = get_image_from_url(image_url) frame = cv2.resize(image_np, im_size) # 将帧图像添加到视频剪辑列表中 video_clips.append(ImageSequenceClip([frame], durations=[frame_duration])) # 创建视频剪辑 video = concatenate_videoclips(video_clips, method="compose") # 加载音频剪辑 audio = AudioFileClip(audio_url) # 将音频添加到视频中 video = video.set_audio(audio) # 保存最终视频 video.write_videofile(video_path, fps=30) create_video_from_images(image_urls, audio_url, video_path)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。