使用Python+OpenCV将多级嵌套文件夹下的视频文件抽帧为JPG图片
import os
import cv2
import time
# 存放视频文件的多层嵌套文件夹路径
videoPath = 'D:\\videos\\'
# 保存抽帧的图片的文件夹路径
savePath = 'D:\\images\\'
if not os.path.exists(savePath):
os.mkdir(savePath)
video_num = 0
for root, dirs, files in os.walk(videoPath):
# 提取多级嵌套文件夹路径下的文件列表
for video in files:
print(video)
if(video.endswith(".avi")):
c = 1
videofile = root + video
vc = cv2.VideoCapture(videofile) #读入视频文件
if vc.isOpened(): #判断是否正常打开
video_num = video_num + 1
rval , frame = vc.read()
#print("正常打开:",video)
if(video_num%100 == 0):
print(video_num)
else:
rval = False
print("打开失败:",video)
continue
timeF = 25 #视频帧计数间隔频率
try:
while rval: #循环读取视频帧
rval, frame = vc.read()
if(c%timeF == 0): #每隔timeF帧进行存储操作
cv2.imwrite(savePath + video[:-4] + '_' + str(time.time_ns()) + '.jpg',frame) #存储为图像
c = c + 1
cv2.waitKey(1)
except:
#print("error")
continue
vc.release()
其中timeF变量是定义视频抽帧间隔频率,可修改