小编给大家分享一下python如何使用openCV遍历文件夹里所有视频文件并保存成图片,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
如果你在文件夹里有很多视频,并且文件夹里还有文件夹,文件夹里的文件夹也有视频,怎么能逐个读取并且保存。。所以我写了个代码用了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如何使用openCV遍历文件夹里所有视频文件并保存成图片”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。