这里实现的是从一段视频中每10帧读取第10帧图片,代码如下:
# -*- coding:utf-8 -*- #视频中按序列提取帧,获得训练数据 import cv2 import os video_src_path = "D:/mtcnn" video_save_path = "D:/mtcnn/mydata" videos = os.listdir(video_src_path) videos = filter(lambda x : x.endswith("mp4") , videos) for each_video in videos: print each_video each_video_name , _ = each_video.split(‘.‘) m = video_save_path + ‘/‘ + each_video_name if(os.path.exists(m) == False): os.mkdir(m) #新建“D:/mtcnn/Mathbook_pic/Mathbook/”文件夹 each_video_save_full_path = os.path.join(video_save_path, each_video_name) + ‘/‘ each_video_full_path = video_src_path + ‘/‘ + each_video print each_video_full_path cap = cv2.VideoCapture(each_video_full_path) if False == cap.isOpened(): print ‘open video failed‘ else: print ‘open video succeeded‘ count = 0 #统计帧数 frame_gap = 10 #间隔为10帧,每个10帧读取第10帧 success = True i = 0 #每隔10帧读取一帧 while(success): success , frame = cap.read() i = i + 1 if(i == frame_gap): #每个10帧读取第10帧 print success #print ‘Read a new frame:‘ , success params = [] params.append(int(cv2.IMWRITE_JPEG_QUALITY)) params.append(95) cv2.imwrite(each_video_save_full_path + each_video_name + ‘_%d.jpg‘ % count , frame , params) count = count + 1 i = 0 cap.release() print ‘OK!‘
注意的是,对于cv2库的VideoCapture函数,如果之前使用的是Pip 安装的opencv的python库,则没有安装FFmPeg,会导致无法正常打开视频,需要按下面步骤进行操作:
参考链接:http://blog.csdn.net/yedasha/article/details/78128345