最近在学习opencv时用到将视频抽帧的问题。用opencv模块可以很方便的做一些跟视频图像分析的研究。下面我借鉴了opencv项目的开源代码改成了demo脚本。
github资源地址
# -*- coding:utf-8 -*-
'''
Simple Cam Test - BGR and Gray
Create by pythonprogramming.net ==> See the tutorial here:
https://pythonprogramming.net/loading-video-python-opencv-tutorial
Adapted by Marcelo Rovai - MJRoBot.org @8Feb18
'''
import numpy as np
import cv2
from hashlib import md5
import os
cap = cv2.VideoCapture(0)
cap.set(1, int(cap.get(7)/2)) #获取视频的中间帧
'''
在当前执行文件环境下,创建抽帧图片存储文件夹
'''
path='facetmp'
os.mkdir(path)
'''
从摄像头获取视频流
'''
while(True):
ret, frame = cap.read()
#print(ret,frame)
frame = cv2.flip(frame, 1)
#print(frame)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('welcome', frame)
cv2.imshow('Gray Windows', gray)
filepath='facetmp/{}.{}'.format(md5(frame).hexdigest(),'jpg')
cv2.imwrite(filepath, frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()