從一段視頻中按幀提取圖片
阿新 • • 發佈:2018-03-14
imp book ima open HA image %d 數據 使用
這裏實現的是從一段視頻中每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
從一段視頻中按幀提取圖片