python --视频分帧,帧合成为图片
pip install opencv-python==4.0.0.21
def video_to_frames(video_path, outPutDirName):
"""
抽取视频帧存为图片
:param video_path:
:param outPutDirName:
:return:
"""
times = 0
# 提取视频的频率,每1帧提取一个
frame_frequency = 1
# 如果文件目录不存在则创建目录
if not os.path.exists(outPutDirName):
os.makedirs(outPutDirName)
# 读取视频帧
camera = cv2.VideoCapture(video_path)
while True:
times = times + 1
res, image = camera.read()
if not res:
print('not res , not image')
break
# 按照设置间隔存储视频帧
if times % frame_frequency == 0:
create_path = os.path.join(outPutDirName, f"{str(times)}.jpg")
cv2.imwrite(create_path, image)
logger.info('图片提取结束')
# 释放摄像头设备
camera.release()
def image_to_video(image_path, media_path, fps):
'''
图片合成视频函数
:param image_path: 图片路径
:param media_path: 合成视频保存路径
:return:
'''
# 获取图片路径下面的所有图片名称
image_names = os.listdir(image_path)
# 对提取到的图片名称进行排序
image_names.sort(key=lambda n: int(n[:-4]))
# 设置写入格式
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
# 设置每秒帧数
fps = fps
# 读取第一个图片获取大小尺寸,因为需要转换成视频的图片大小尺寸是一样的
image = Image.open(os.path.join(image_path, image_names[0]))
# 初始化媒体写入对象
media_writer = cv2.VideoWriter(media_path, fourcc, fps, image.size)
# 遍历图片,将每张图片加入视频当中
for image_name in image_names:
im = cv2.imread(os.path.join(image_path, image_name))
media_writer.write(im)
# 释放媒体写入对象
media_writer.release()
logger.info('无声视频写入完成!')