有时候需要将视频中每帧都保存为图像,便于后续的图像处理
moviepy方法
使用moviepy中clip的iter_frames方法即可:
import os
from moviepy.editor import *
from PIL import Image
if __name__ == '__main__':
"""
将视频保存为图片
"""
videofile = 'sample.mp4'
video_clip = VideoFileClip(videofile)
# creating a folder to save Images if folder not existed
if not os.path.exists('Image_frames'):
os.makedirs('Images_frames')
for idx, frame in enumerate(video_clip.iter_frames()):
print(">>>idx: ", idx)
filename = './Images_frames/frame' + str(int(idx)) + ".png"
Image.fromarray(frame).save(filename)
video_clip.close()
print("Done!")
注意最好保存图像为png格式,png能够保存透明度,而且是无损压缩
opencv方法
以下代码使用opencv的视频处理代码实现:
import os
import cv2
if __name__ &