MoivePy是一个用于视频编辑的Python库,可以:剪切、拼接、标题插入、视频合成、视频处理和创建自定义效果。它支持Windows、Linux、Mac,源码地址:https://github.com/Zulko/moviepy,最新发布版本v1.0.3,license为MIT。
windows上安装MoivePy:
(1).从https://imagemagick.org/script/download.php 下载ImageMagick-7.1.1-10-Q16-HDRI-x64-dll.exe进行默认安装,可通过cmd,执行"magick --version"验证是否安装成功;
(2).安装moivepy,执行:pip install moviepy
(3).执行测试代码时,如果报ImageMagick的错误,如"This error can be due to the fact that ImageMagick is not installed on your computer",安装ImageMagick时,已经加入到系统环境变量中了,但是还是报错,可通过修改Anaconda3/envs/OpenCV_Test/Lib/site-packages/moviepy目录下的config_defaults.py文件解决:
IMAGEMAGICK_BINARY = os.getenv('IMAGEMAGICK_BINARY', 'auto-detect') # 原语句
IMAGEMAGICK_BINARY = os.getenv('IMAGEMAGICK_BINARY', 'C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\magick.exe') # 修改后
测试代码,通过MoviePy给视频添加文本或图像:
import moviepy.editor as mp
import cv2
def add_text(filename, text, font, fontsize, color, pos, result):
clip = mp.VideoFileClip(filename)
#clip = clip.subclip(10, 20) # 仅clip 10到20秒之间的视频
#print(f"duration: {clip.duration} seconds") # 视频文件clip的持续时间
txt_clip = (mp.TextClip(text, font=font, fontsize=fontsize, color=color)
.set_position(pos)
.set_duration(clip.duration))
#print(f"color list:\n {mp.TextClip.list('color')}") # 支持的color列表
#print(f"font list:\n {mp.TextClip.list('font')}") # 支持的font列表
final = mp.CompositeVideoClip([clip, txt_clip]) # 将文本叠加在视频上
final.write_videofile(result, fps=clip.fps, codec="libx264")
def add_image(filename, image, pos, width, height, result):
clip = mp.VideoFileClip(filename)
#clip = clip.subclip(10, 20)
mat = cv2.imread(image)
mat = cv2.resize(mat, (width, height))
#img_clip = (mp.ImageClip(image)
img_clip = (mp.ImageClip(mat)
.set_position(pos)
.set_duration(clip.duration)
.set_opacity(0.5)) # 设置不透明度/透明度级别
final = mp.CompositeVideoClip([clip, img_clip]) # 将图像叠加在视频上
final.write_videofile(result, fps=clip.fps, codec="libx264")
if __name__ == "__main__":
filename = "../../test_images/123.mp4"
pos = (100, 100) # 左上角坐标(x, y)
#pos = ("left", "center") # center, right, left, bottom, top
text = "北京 fengbingchun"
font = "Simhei" # "华文彩云" ...
fontsize = 75
color = "red" # green, black, blue, red ...
result = "../../test_images/result_text.mp4"
add_text(filename, text, font, fontsize, color, pos, result)
image = "../../test_images/1.jpg"
result = "../../test_images/result_image.mp4"
width = 128
height = 64
add_image(filename, image, pos, width, height, result)
print("test finish")
执行结果如下图所示:也可同时将文本和图像添加到视频中,mp.CompositeVideoClip接收的参数是列表,调整为:mp.CompositeVideoClip([clip, txt_clip, img_clip])即可
GitHub:http://github.com/fengbingchun/OpenCV_Test