欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python使用openCV遍历文件夹里所有视频文件并保存成图片

时间:2021-06-07 08:54:58|栏目:Python代码|点击:

如果你在文件夹里有很多视频,并且文件夹里还有文件夹,文件夹里的文件夹也有视频,怎么能逐个读取并且保存。。所以我写了个代码用了os,walk,这个可以遍历所有文件夹里的文件和文件夹

import os
import cv2
cut_frame = 250 # 多少帧截一次,自己设置就行
save_path = "C:\文献与资料\手持红外\图片"
for root, dirs, files in os.walk(r"C:\文献与资料\手持红外"): # 这里就填文件夹目录就可以了
 for file in files:
 # 获取文件路径
 if ('.mp4' in file):
  path = os.path.join(root, file)
  video = cv2.VideoCapture(path)
  video_fps = int(video.get(cv2.CAP_PROP_FPS))
  print(video_fps)
  current_frame = 0
  while (True):
  ret, image = video.read()
  current_frame = current_frame + 1
  if ret is False:
   video.release()
   break
  if current_frame % cut_frame == 0:
   # cv2.imwrite(save_path + '/' + file[:-4] + str(current_frame) + '.jpg',
   #  image) # file[:-4]是去掉了".mp4"后缀名,这里我的命名格式是,视频文件名+当前帧数+.jpg,使用imwrite就不能有中文路径和中文文件名
   cv2.imencode('.jpg', image)[1].tofile(save_path + '/' + file[:-4] + str(current_frame) + '.jpg') #使用imencode就可以整个路径中可以包括中文,文件名也可以是中文
   print('正在保存' + file + save_path + '/' + file[:-4] + str(current_frame))

ps:下面看下python 遍历文件夹

import os
# 遍历文件夹
def walkFile(file):
 for root, dirs, files in os.walk(file):
 # root 表示当前正在访问的文件夹路径
 # dirs 表示该文件夹下的子目录名list
 # files 表示该文件夹下的文件list
 # 遍历文件
 for f in files:
  print(os.path.join(root, f))
 # 遍历所有的文件夹
 for d in dirs:
  print(os.path.join(root, d))
def main():
 walkFile("f:/ostest/")
if __name__ == '__main__':
 main()

总结

上一篇:Python中用于转换字母为小写的lower()方法使用简介

栏    目:Python代码

下一篇:总结Python编程中函数的使用要点

本文标题:python使用openCV遍历文件夹里所有视频文件并保存成图片

本文地址:http://www.codeinn.net/misctech/137165.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有