pythonopencv 视频裁剪成帧。全帧、自定义间隔帧、只取某一帧

# coding: utf-8
import cv2 as cv
import os
print('===============================================================')
print('按照全帧截取视频帧率照片(默认未裁剪图片,如不需要请更改代码---时间有点久,请稍等…………')
print('===============================================================')
filepath = './input'          
pathDir = os.listdir(filepath)  
for allDir in pathDir:          
	Frame = 1  
	c = 1  
	videopath = r'./input/'+allDir  
	vc = cv.VideoCapture(videopath) 
	path = './Video_Result(All)Frame/'
	if not os.path.exists(path):   
		os.mkdir(path)
	if vc.isOpened(): 
		rval , frame = vc.read()
	else:
		rval = False
	timeF = 1                    
	while rval:
		rval,frame = vc.read()     
		if rval==False:
			break
		if(c%timeF==0):	
			#frame = frame[0:1070,200:1840]
			cv.imencode('.jpg',frame)[1].tofile(path +'/' + str(Frame) +'-'+ allDir[:-4] + '.jpg')    
			print('正在截取第' + str(Frame) + "帧,请稍后……")
			Frame += 1
print('
','处理完成,请移步------→ :Video_Result(All)Frame查看结果')
# coding: utf-8
import cv2 as cv
import os
print('===============================================================')
print('按照间隔20帧(可自定义)帧截取视频帧率照片(默认未裁剪图片,如不需要请更改代码,---请稍等…………)')
print('===============================================================')
filepath = './input'            
pathDir = os.listdir(filepath) 
for allDir in pathDir:       
	a = 1 
	c = 1  
	videopath = r'./input/'+allDir  
	vc = cv.VideoCapture(videopath) 
	path = './Video_Result(Interval)Frame/'
	if not os.path.exists(path):   
		os.mkdir(path)
	if vc.isOpened(): 
		rval , frame = vc.read()
	else:
		rval = False
	timeF = 20                       
	while rval:
		rval,frame = vc.read()      
		if rval==False:
			break
		if(c%timeF==0):
			cv.imencode('.jpg',frame)[1].tofile(path +'/' + str(a) +'-'+ allDir[:-4] + '.jpg')    
			print('正在截取第' + str(a) + "帧,请稍后……")
		a += 1
		c += 1
		cv.waitKey(1)
	vc.release()
print('
','处理完成,请移步------→ :Video_Result(Interval)Frame查看结果')
# coding: utf-8
import cv2 as cv
import os
print('===============================================================')
print('自定义设置指定帧数进行截取(每个视频截取一幅图片)---请稍等……')
print('===============================================================','
')
filepath = './input'            
pathDir = os.listdir(filepath) 
for allDir in pathDir:          
	a = 80
	videopath = r'./input/'+allDir  
	vc = cv.VideoCapture(videopath) 
	path = './Video_Result(Only-1)Frame/'
	if not os.path.exists(path):    
		os.mkdir(path)
	if vc.isOpened(): 
		rval , frame = vc.read()
	else:
		rval = False
	while rval:
		vc.set(cv.CAP_PROP_POS_FRAMES, a)
		rval,frame = vc.read()     
		cv.imencode('.jpg',frame)[1].tofile(path +'/' + str(a) +'-'+ allDir[:-4] + '.jpg')  
		print(str(a) +'-'+ allDir[:-4] + '---视频截取完成')
		break
print('
','处理完成,请移步------→ :Video_Result(Only-1)Frame查看结果')
原文地址:https://www.cnblogs.com/Tdazheng/p/13745362.html