Code
因为工作需要,写了一段代码用于在视频中提取帧图片:
# coding=utf-8
# 全局变量
VIDEO_PATH = './1.avi' # 视频地址
EXTRACT_FOLDER = './extract_folder' # 存放帧图片的位置
EXTRACT_FREQUENCY = 100 # 帧提取频率
def extract_frames(video_path, dst_folder, index):
# 主操作
import cv2
video = cv2.VideoCapture()
if not video.open(video_path):
print("can not open the video")
exit(1)
count = 1
while True:
_, frame = video.read()
if frame is None:
break
if count % EXTRACT_FREQUENCY == 0:
save_path = "{}/{:>03d}.jpg".format(dst_folder, index)
cv2.imwrite(save_path, frame)
index += 1
count += 1
video.release()
# 打印出所提取帧的总数
print("Totally save {:d} pics".format(index-1))
def main():
# 递归删除之前存放帧图片的文件夹,并新建一个
import shutil
try:
shutil.rmtree(EXTRACT_FOLDER)
except OSError:
pass
import os
os.mkdir(EXTRACT_FOLDER)
# 抽取帧图片,并保存到指定路径
extract_frames(VIDEO_PATH, EXTRACT_FOLDER, 1)
if __name__ == '__main__':
main()
Note:
获取该视频的帧率:
cap = cv2.VideoCapture(C.in_dir + video_name)
C.fps = round(cap.get(cv2.CAP_PROP_FPS))
Attach
其中,如何设置合理的 帧提取频率 ,可参考我的另一篇blog:《常见帧率 与 帧率运用》